PythoncTypes:类型转换

PythoncTypes:类型转换,python,ctypes,Python,Ctypes,是否可以使用argtypes属性将Pythonint自动转换为ctypes整数指针 例如 我希望可以使用argtypes属性来自动转换python整数……但是我得到了一个错误 <type 'exceptions.TypeError'>: expected LP_c_int instance instead of int 但是有点冗长,尤其是有多个参数 没有自动转换为指针类型 指针(c_int)是指向c整数的指针,表示存储,通常表示它是一个输出参数。如果调用了somefunc(7),

是否可以使用
argtypes
属性将Python
int
自动转换为ctypes整数指针

例如

我希望可以使用
argtypes
属性来自动转换python整数……但是我得到了一个错误

<type 'exceptions.TypeError'>: expected LP_c_int instance instead of int

但是有点冗长,尤其是有多个参数

没有自动转换为指针类型

指针(c_int)
是指向c整数的指针,表示存储,通常表示它是一个输出参数。如果调用了
somefunc(7)
,那么输出值会到哪里去

显然,这是可行的:

cfunc(ctypes.byref(ctypes.c_int(i)))
cfunc(ctypes.byref(ctypes.c_int(i)))

不是很明显,如果C
int*
被写入,那么您已经创建了一个临时C int存储值。如果
cfunc
写入该存储器,则函数返回后会立即释放该存储器,并且无法访问该值。因此,您必须创建存储并将其分配给变量,以保持引用足够长的时间来检索值:

v = ctypes.c_int(100)   # Create C int storage for Python int 100.
cfunc(ctypes.byref(v))  # Pass 100 by reference into the function
print(v.value)          # Retrieve the returned C int as a Python int.

从ctypes导入c_int、byref等
使行大大缩短。:)
来自ctypes,由_ref导入为R
甚至更多。关于我的“显然”评论,这是一个很好的观点……我早些时候得出了类似的结论!
v = ctypes.c_int(100)   # Create C int storage for Python int 100.
cfunc(ctypes.byref(v))  # Pass 100 by reference into the function
print(v.value)          # Retrieve the returned C int as a Python int.