今天通过一个实例和大家分享一下Python调用C语言DLL的简单调用过程,希望对大家有所帮助和启发。我的程序编译运行环境简单说明一下,本文介绍的C程序使用mingw下使用gcc编译运行,Python使用windows下安装的Python3.9版本。本次分享实例中的程序文件及编译的库文件、可执行程序文件如下图所示:
首先,我们来编写一个简单的C程序add.c,并将其编译为一个dll库,这个小程序我们来实现两个函数,分别实现整型数(int)和符点型数(float)的相加。程序如下:
#include
__declspec(dllexport) int addint(int a, int b);
__declspec(dllexport) float addfloat(float a, float b);
int addint(int, int);
float addfloat(float, float);
int addint (int num1,int num2)
{
return num1 + num2;
}
float addfloat(float num1, float num2)
{
return num1 + num2 ;
}
使用下面的语句将其编译成一个dll,执行后生成testadd.dll和testadd.lib文件。
gcc -shared -Wl,--out-implib,testadd.lib -o testadd.dll -fPIC add.c
下面,编写一个C语言程序,验证库文件没有问题,可以正常使用,代码如下:
__declspec(dllimport) int __stdcall addint(int a, int b);
//__declspec(dllimport) 导入包
// 静态调用DLL库
int main()
{
HMODULE h = NULL;//创建一个句柄h
h = LoadLibrary("testadd.dll");
if (h == NULL)//检测是否加载dll成功
{
printf("加载testadd.dll动态库失败\n");
return -1;
}
typedef int(*AddFunc)(int, int); // 定义函数指针类型
AddFunc add;
// 导出函数地址
add = (AddFunc)GetProcAddress(h, "add");
int sum = addint(10, 20);
printf("静态调用,sum = %d\n", sum);
}
使用gcc将其编译生成可执行文件cadd.exe。
mingw中在程序所在目录执行以下命令,可以看到程序正常返回10+20的执行结果:
$ ./cadd.exe
静态调用,sum = 30
现在,我们来编辑一个python程序,用来调用刚刚编译好的testadd.dll,这里注意要用到ctypes库,代码如下:
from ctypes import *
#load the shared object file
adder = CDLL('testadd.dll', winmode=0)
#Find sum of integers
res_int = adder.addint (8,10)
print("sum of 8 and 10 = " + str(res_int))
#Find sum of floats
a = c_float(6.5)
b= c_float(9.8)
add_float = adder.addfloat
add_float.restype = c_float
print('sum of 6.5 and 9.8 =%.2f'%add_float(a, b))
最后,运行以上代码,执行结果如下:
至此,我们已经成功完成Python对C语言库的调用,你学会了吗?希望简单的分享对大家有所帮助。