使用pycharm用python调用C生成的动态链接库(DLL)
通常使用内置ctypes模块完成DLL中c变量类型与python变量类型的对应。确认DLL所在地址后使用cdll.LoadLibrary(dll所在地址)完成DLL的加载。
# -*- coding:utf-8 -*- # # Author:LucXiong # import ctypes from ctypes import * address = 'C:\\Users\\HUAWEI\\Documents\\\codeblocks生成dll并调用\\fordll\\bin\Debug\\fordll.dll' dll = cdll.LoadLibrary(address)首先,将dll内函数赋给add1 然后,通过.argtypes = [数据类型]与dll内已写好的函数输入参数类型对应,通过.restype =与与dll内已写好的函数返回参数类型对应。此处dll内函数具体定义代码见【codeblocks】C生成并调用DLL。
// dll内无指针函数 int add1(int a, int b) { int c; c = a + b; return c; } # python调用无指针函数 add1 = dll.add1 add1.argtypes = [c_int,c_int] add1.restype = c_int t1 = 23 t2 = 24 x = add1(t1,t2) print(x) # 47 print(type(x)) # <class 'int'>最后,即可直接由add1(t1,t2)完成dll内函数的调用。输出数据也为python的int类型。
首先,将dll内函数赋给add2 然后,通过.argtypes = [数据类型]与dll内已写好的函数输入参数类型对应,通过.restype =与与dll内已写好的函数返回参数类型对应。非字符串指针的对应通过POINTER(c_float)、POINTER(c_int)完成对应,具体各数据类型的对应关系见参考资料[4]python ctypes模块中变量与c对应关系。此处dll内函数具体定义代码见【codeblocks】C生成并调用DLL。
// ddl内入参浮点,返回指针数组的函数 float *add2(float a, float b) { static float c[2]; c[0] = a + b; c[1] = c[0] + 1; return c; } # python调用dll内入参浮点,返回指针数组的函数 add2 = dll.add2 add2.argtypes = [c_float,c_float] add2.restype = POINTER(c_float) t1 = 23 t2 = 24 y = add2(t1,t2) print(y) # <__main__.LP_c_float object at 0x045A6D00> print(type(y)) # <class '__main__.LP_c_float'> print(y[0]) # 47.0 print(type(y[0])) # <class 'float'>最后,即可直接由add2(t1,t2)完成dll内函数的调用。但是由于返回为指针,所以看到输出为print(y) # <__main__.LP_c_float object at 0x045A6D00>,数据类型是<class '__main__.LP_c_float'>,根据指针数组与python列表的相似性,直接通过y[0]即可取出原dll指针数组中的值。
首先,将dll内函数赋给add3 然后,通过.argtypes = [数据类型]与dll内已写好的函数输入参数类型对应(即使入参为一个参数,也需要用[]标记),通过.restype =与与dll内已写好的函数返回参数类型对应。非字符串指针的对应通过POINTER(c_float)、POINTER(c_int)完成对应,具体各数据类型的对应关系见参考资料[4]python ctypes模块中变量与c对应关系。此处dll内函数具体定义代码见【codeblocks】C生成并调用DLL。
// dll内入参指针数组,返回浮点的函数 float add3(float *arr) { float c; c = arr[0] + arr[1]; return c; } # python调用dll内入参指针数组,返回浮点的函数 add3 = dll.add3 add3.argtypes = [POINTER(c_float)] add3.restype = c_float t1 = 23 t2 = 24 t = (c_float*2)(*[t1,t2]) # important! # print(type(t)) # cast(t,POINTER(c_float)) # print(type(t)) z = add3(t) print(z) # 47.0 print(type(z)) # <class 'float'>第三步,在通过add3(t)调用函数dll内函数之前,需要将输入参数对应的某一数组(python里 的列表)转化成符合要求的指针数组(即上述代码第7行)(c_float*2)(*[t1,t2])即(c数据类型*列表长度)(*列表)。最后即可直接由add3(t)完成dll内函数的调用。具体见参考资料[3] python调用dll第三篇:python调用dll代码编写运行
[1] python DLL文件调用问题 [2] Python ctypes 使用总结 [3] python调用dll第三篇:python调用dll代码编写运行 [4] python ctypes模块中变量与c对应关系 如有侵权,请发送邮件至lxiong13@outlook.com联系我!Merci beaucoup!
