我正在创建一个 ctype 结构。我有一个外部函数,需要将指向该结构的指针传递给它。 ctype 结构中应该有一个 void 指针。
示例函数原型(prototype):
ExtFunc(
TestStruct* myVoidStruct
);
其中我的 C 等效结构定义如下:
typedef struct voidStruct
{
void* voidField;
} voidStruct;
我尝试创建这样的结构,但 Python 总是将 void 指针解释为 void 指针以外的东西。
这会产生什么影响(如果有的话)?这是否意味着外部函数也将结构的这个元素解释为除 void 指针之外的其他元素?
>>> class TestStruct(ctypes.Structure):
_fields_ = [("voidField", ctypes.c_void_p)]
>>> x = TestStruct()
立即,voidField 返回为 NoneType
>>> type(x.voidField)
<type 'NoneType'>
但是,我可以在结构之外创建并维护一个 void 指针:
>>> y = ctypes.c_void_p(123)
>>> y
c_void_p(123L)
正如我上面所说,我将结构传递给外部函数。当函数完成时,结构元素的类型为“long”,并具有关联值
>>> x.voidField
88145984L
>>> type(x.voidField)
<type 'long'>
为什么现在是 long 类型?而它的值(value)又有何意义呢?这是指针的内存地址吗?指针指向的内存地址?还是它所指向的内存地址的前几个字节的值?
最佳答案
And right off the bat, voidField returns as a NoneType
这只是因为 NULL
指针被转换为 Python None
...
>>> from ctypes import *
>>> class TestStruct(Structure):
... _fields_ = [("voidField", c_void_p)]
...
>>> x.voidField = 0
>>> print repr(x.voidField)
None
Why is it now a type long?
一旦将指针设置为非零值,它将是 Python int
或 Python long
...
>>> x.voidField = 123
>>> print repr(x.voidField)
123
And what is the significance of its value?
它是 void *
指针指向的地址,即您可以从类似...的内容中获得的内容
void* ptr = malloc(1000);
printf("%ld\n", (long) ptr);
关于Python Ctypes 将 void 指针转换为 nonetype 和 long。有什么影响?这是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17372519/