我正在尝试使用Python与" ReturnBuffer"我创建的DLL中的函数,并遇到了缓冲值似乎没有被函数修改的问题。 " ReturnBuffer"函数有两个参数,缓冲区的长度和指向缓冲区的指针,我想知道我是否正确传递指针。我写了c函数,如下所示:
__declspec(dllexport) int ReturnBuffer (int num_numbers, unsigned __int32 *buffer);
int ReturnBuffer (int num_numbers, unsigned __int32 *buffer)
{
int i;
for (i = 0; i < num_numbers; i++) {
buffer[i] = buffer[i] + i ;
}
return 1;
}
我使用下面的python代码加载DLL:
_file = 'MyMathDLL.dll'
_path = os.path.join(*(os.path.split(__file__)[:-1] + (_file,)))
_math = ctypes.cdll.LoadLibrary(_path)
然后我创建一个1的数组并将数组的长度和数组的指针传递给函数&#34; ReturnBuffer&#34;,我的期望是该函数将获取指针并修改缓冲区中的值。
_math.ReturnBuffer.restype = ctypes.c_int
_math.ReturnBuffer.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint32)]
nelem = 10
variable = ctypes.c_double(10.0)
Buffer_Type = ctypes.c_uint32 * nelem
Buffer = (1,1,1,1,1,1,1,1,1,1)
print(_math.ReturnBuffer(ctypes.c_int(nelem),Buffer_Type(*Buffer)))
print(Buffer)
Screen Output:
1
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
Process finished with exit code 0
答案 0 :(得分:0)
数组初始化在文档中描述:https://docs.python.org/2/library/ctypes.html
试试这个:
Buffer = (ctypes.c_uint32 * nelem)()
for i in range(0, nelem):
Buffer[i] = 1
print(_math.ReturnBuffer(nelem, Buffer))
print(Buffer)
或者这个:
Buffer = (ctypes.c_uint32 * nelem)(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
print(_math.ReturnBuffer(nelem, Buffer))
print(Buffer)