简体   繁体   中英

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. The "ReturnBuffer" function take two arguments, length of buffer and pointer to the buffer, I am wondering if I am passing the pointer correctly. I have written the c function as shown below:

__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:

_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.

_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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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