test.dll文件功能代码:
double __cdecl add(int len,double array[]){}
(而且我已经在vc中测试过了)
python 代码:
import ctypes
from ctypes import *
N=...
arr=(c_double*N)()
...
...
dll=CDLL("test.dll")
sum=dll.add(c_int(N),byref(arr))
print sum
但是 python 代码不起作用, 并且“总和”总是等于 N 。(即当 N=10 时,它打印“总和=10”) 有什么问题吗?
最佳答案
在 ctypes 中传递数组反射(reflect)了在 C 中传递数组,即您不需要传递对它的引用,因为数组已经是对其第一个元素的引用。
from ctypes import *
N = ...
arr=(c_double*N)()
dll=CDLL("test.dll")
sum=dll.add(c_int(N),arr)
print sum
这方面的一个例子可以在 callbacks section 下的 ctypes 文档中看到。在讨论与 qsort 的接口(interface)时。
编辑:根据 David Heffernan 的评论,您还需要 dll.add.restype = c_double
,否则 ctypes 将假定返回的类型为 c_int
。
关于python - 如何将数组传递给使用 python 用 c 编写的共享库 (.dll),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9873678/