问题描述
我有一个包含C函数的DLL,其原型如下:
I have a DLL containing a C function with a prototype like this:
int c_read_block(uint32 addr, uint32 *buf, uint32 num);
我想使用ctypes从Python调用它.该函数需要一个指向大块内存的指针,它将结果写入其中.我不知道如何构造和传递这么大的内存. ctypes文档没有太大帮助.
I want to call it from Python using ctypes. The function expects a pointer to a chunk of memory, into which it will write the results. I don't know how to construct and pass such a chunk of memory. The ctypes documentation isn't much help.
构造一个数组并将其传递给"byref",如下所示:
Constructing an array and passing it "byref", like this:
cresult = (c_ulong * num)()
err = self.c_read_block(addr, byref(cresult), num)
给出此错误消息:
ArgumentError: argument 3: <type 'exceptions.TypeError'>: expected LP_c_ulong instance instead of pointer to c_ulong_Array_2
我猜这是因为Python ulong数组与c uint32数组完全不同.我应该使用create_char_string
吗?如果是这样,我该如何说服Python将缓冲区投射"到LP_c_ulong?
I guess that is because the Python ulong array is nothing like a c uint32 array. Should I use create_char_string
. If so, how do I persuade Python to "cast" that buffer to an LP_c_ulong?
推荐答案
您可以使用 cast
函数:)
You can cast with the cast
function :)
>>> import ctypes
>>> x = (ctypes.c_ulong*5)()
>>> x
<__main__.c_ulong_Array_5 object at 0x00C2DB20>
>>> ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong))
<__main__.LP_c_ulong object at 0x0119FD00>
>>>
这篇关于Python ctypes中的指针和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!