简体   繁体   English

通过Python中的Ctypes将指针传递给DLL

[英]Passing pointer to DLL via Ctypes in Python

I am trying to use Python to interface with "ReturnBuffer" function in the DLL I created and have run into the problem where the buffer values does not seem to be modified by the function. 我正在尝试使用Python与我创建的DLL中的“ ReturnBuffer”函数进行接口,并遇到了缓冲区值似乎未被该函数修改的问题。 The "ReturnBuffer" function take two arguments, length of buffer and pointer to the buffer, I am wondering if I am passing the pointer correctly. “ ReturnBuffer”函数采用两个参数,即缓冲区的长度和指向缓冲区的指针,我想知道是否正确地传递了指针。 I have written the c function as shown below: 我编写了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;
}

I load the DLL using python code below: 我使用下面的python代码加载DLL:

_file = 'MyMathDLL.dll'
_path = os.path.join(*(os.path.split(__file__)[:-1] + (_file,)))
_math = ctypes.cdll.LoadLibrary(_path)

Then I create an array of 1's and pass the length of the array and the pointer of the array to function "ReturnBuffer", my expectation is that the function will take the pointer and modify the values in the buffer. 然后,我创建一个1的数组并将该数组的长度和该数组的指针传递给函数“ ReturnBuffer”,我期望该函数将采用该指针并修改缓冲区中的值。

_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

Array initialization is described in the docs: https://docs.python.org/2/library/ctypes.html 数组初始化在docs中进行了描述: https : //docs.python.org/2/library/ctypes.html

Try this: 尝试这个:

Buffer = (ctypes.c_uint32 * nelem)()
for i in range(0, nelem):
    Buffer[i] = 1
print(_math.ReturnBuffer(nelem, Buffer))
print(Buffer)

or this: 或这个:

Buffer = (ctypes.c_uint32 * nelem)(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
print(_math.ReturnBuffer(nelem, Buffer))
print(Buffer)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM