Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么设置ctypes dll.function.restype=c\u void\u p会返回很长的时间?_Python_Ctypes - Fatal编程技术网

Python 为什么设置ctypes dll.function.restype=c\u void\u p会返回很长的时间?

Python 为什么设置ctypes dll.function.restype=c\u void\u p会返回很长的时间?,python,ctypes,Python,Ctypes,奇怪的是,即使设置了restype,python仍然返回long,而不是c\u void\u p 比如, # python code from ctypes import * dll = windll.LoadLibrary("my.dll") dll.my_object_create.restype = c_void_p x = dll.my_object_create() print type(x) # prints <type 'long'> //c++ code my_ob

奇怪的是,即使设置了
restype
,python仍然返回
long
,而不是
c\u void\u p

比如,

# python code
from ctypes import *
dll = windll.LoadLibrary("my.dll")
dll.my_object_create.restype = c_void_p
x = dll.my_object_create()
print type(x) # prints <type 'long'>

//c++ code
my_object *my_object_create() { return new my_object(); }
void my_object_destroy(my_object *obj) { delete obj; }
…我猜在某种程度上,ctypes将
x
视为4字节而不是8字节(64位体系结构)

因此,我想知道,现有的行为是否会导致您陷入这种陷阱?

的用途。如果地址适合平台
long
,则返回Python
int
;否则,它将返回一个Python
long
,其精度是可变的。这很好,但是当将这个整数值作为参数传递时,默认行为是to,在所有支持的平台上都是32位的

我认为最好的解决方案是设置
argtypes
,将参数正确地转换为指针类型。另一个选项是将
restype
设置为
c\u void\u p
的子类。使用子类将禁用到Python整数的转换。通过调用来检查这一点,这实际上返回了其名称和源注释建议的相反内容。(在2.5中,该函数被命名,而源注释在当时也是错误的。所讨论的“简单”不是元类,而是基类型。)

POSIX:

#将解释器配置为加载可见扩展名-
#模块符号,如_ctypes_simple_instance,
#进入全局符号表。
导入系统,DLFCN
sys.setdlopenflags((sys.getdlopenflags()&~DLFCN.RTLD_LOCAL)|
DLFCN.RTLD_(全球)
从ctypes导入*
_ctypes\u simple\u instance=PyDLL(无)。\u ctypes\u simple\u instance
_ctypes\u simple\u instance.argtypes=py\u对象,
malloc=CDLL(无)。malloc
类别my_void_p(c_void_p):
通过
>>\u ctypes\u simple\u实例(c\u void\u p)
0
>>>_ctypes_simple_实例(my_void_p)
1.
>>>malloc.restype=c\u void\u p
>>>类型(malloc(100))
>>>malloc.restype=my\u void\u p
>>>类型(malloc(100))
窗口:

\u ctypes\u simple\u实例
不是由_ctypes.pyd导出的

从ctypes导入*
malloc=cdll.msvcrt.malloc
类别my_void_p(c_void_p):
通过
>>malloc.restype=c\u void\u p
>>>类型(malloc(100))
>>>malloc.restype=my\u void\u p
>>>类型(malloc(100))

这是一种预期行为。如果重新类型是简单的ctypes类型(
c_int
c_void\u p
),则
ctypes
将调用类型的
getfunc
,而不是重新类型。看见
x = c_void_p(dll.my_object_create())