I have a DLL containing a C function with a prototype like this:
我有一个DLL包含一个C函数,它的原型是这样的:
int c_read_block(uint32 addr, uint32 *buf, uint32 num);
int c_read_block(uint32 addr, uint32 *buf, uint32 num);
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.
我想使用ctype从Python中调用它。该函数期望指向内存块的指针,并将其写入结果。我不知道如何构造并传递这样一块内存。ctypes文档并没有多大帮助。
Constructing an array and passing it "byref", like this:
构造一个数组并通过它“byref”,如下所示:
cresult = (c_ulong * num)() err = self.c_read_block(addr, byref(cresult), num)
Gives this error message:
让这个错误信息:
ArgumentError: argument 3: <type 'exceptions.TypeError'>: expected LP_c_ulong instance instead of pointer to c_ulong_Array_2
参数3:
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?
我猜那是因为Python ulong数组与c uint32数组完全不同。我应该使用create_char_string。如果是,我如何说服Python将该缓冲区“cast”到LP_c_ulong?
2 个解决方案
#1
49
You can cast with the cast
function :)
您可以使用cast功能:)
>>> 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>
>>>
#2
-1
There is a typo in the solution. In order to get a pointer to an array of ulongs you need to cast to a POINTER(list of ulong)
解决方案中有一个错误。为了获得指向ulongs数组的指针,你需要将它转换为一个指针(ulong列表)
In [33]: ptr = ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong*5))
In [34]: ptr
Out[34]: <__main__.LP_c_ulong_Array_5 at 0x23e2560>
#1
49
You can cast with the cast
function :)
您可以使用cast功能:)
>>> 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>
>>>
#2
-1
There is a typo in the solution. In order to get a pointer to an array of ulongs you need to cast to a POINTER(list of ulong)
解决方案中有一个错误。为了获得指向ulongs数组的指针,你需要将它转换为一个指针(ulong列表)
In [33]: ptr = ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong*5))
In [34]: ptr
Out[34]: <__main__.LP_c_ulong_Array_5 at 0x23e2560>