在[Python 3]:类型转换中介绍了如何处理指针和数组。
我为您准备了一个虚拟的例子。
main.c :
#if defined(_WIN32)# define DECLSPEC_DLLEXPORT __declspec(dllexport)#else# define DECLSPEC_DLLEXPORT#endifstatic int kSize = 5;DECLSPEC_DLLEXPORT int size() { return kSize;}DECLSPEC_DLLEXPORT int function(int dummy, float *data1, float *data2) { for (int i = 0; i < kSize; i++) { data1[i] = dummy * i; data2[i] = -dummy * (i + 1); } return 0;}pre.py :
#!/usr/bin/env pythonimport sysimport ctypesc_float_p = ctypes.POINTER(ctypes.c_float)def main(): dll_dll = ctypes.CDLL("./dll.so") size_func = dll_dll.size size_func.argtypes = [] size_func.restype = ctypes.c_int function_func = dll_dll.function function_func.argtypes = [ctypes.c_int, c_float_p, c_float_p] function_func.restype = ctypes.c_int size = size_func() print(size) data1 = (ctypes.c_float * size)() data2 = (ctypes.c_float * size)() res = function_func(1, ctypes.cast(data1, c_float_p), ctypes.cast(data2, c_float_p)) for i in range(size): print(data1[i], data2[i])if __name__ == "__main__": print("Python {:s} on {:s}n".format(sys.version, sys.platform)) main()注意事项 :
- 该 Ç 部分试图模仿你的什么 的.dll 做(或者至少是我的理解):
- size- 获取数组大小
- 函数 -填充数组(直到其大小-假设调用方已正确分配了它们)
- Python 部分很简单:
- 加载 .dll
- 定义 argtypes 和 restype (在你的代码它的 restype ‘ Ş 为2个函数)(用于 size_func 没有必要)
- 得到长度
- 初始化数组
- 通过他们 function_func 使用
ctypes.cast
输出 (在 Lnx上 ,因为构建 C 代码要简单得多,但在 Win 上也可以使用):
[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q050043861]> gcc-shared -o dll.so main.c
[cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q050043861]> python3
pre.py
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux50.0 -1.01.0 -2.02.0 -3.03.0 -4.04.0 -5.0



