Python Ctypes converts void pointer to nonetype and long. What are the implications? What does this mean?

StackOverflow https://stackoverflow.com/questions/17372519

문제

I'm creating a ctype structure. I have an external function that requires a pointer to this structure be passed to it. The ctype structure is supposed to have a void pointer in it.

Example function prototype:

ExtFunc(
TestStruct* myVoidStruct
);

where my C-equivalent structure is defined as follows:

typedef struct voidStruct
{
    void* voidField;
} voidStruct;

I attempt to create such a structure, but invariably the void pointer is interpreted by Python as being something other than a void pointer.

What are the implications of this, if any? Does this mean that the external function is also interpreting this element of the structure as something other than a void pointer?

>>> class TestStruct(ctypes.Structure):
    _fields_ = [("voidField", ctypes.c_void_p)]

>>> x = TestStruct()

And right off the bat, voidField returns as a NoneType

>>> type(x.voidField)
<type 'NoneType'>

But, I can create and sustain a void pointer outside of a structure:

>>> y = ctypes.c_void_p(123)
>>> y
c_void_p(123L)

As I said above, I'm passing my structure to an external function. When the function completes, the structure elements is of type 'long', with an associated value

>>> x.voidField
88145984L
>>> type(x.voidField)
<type 'long'>

Why is it now a type long? And what is the significance of its value? Is this the memory address of the pointer? The memory address to where the pointer is pointing? Or is it the value of the first several bytes at the memory address to which it is pointing?

도움이 되었습니까?

해결책

And right off the bat, voidField returns as a NoneType

This is just because the NULL pointer is translated to 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?

As soon as you set the pointer to something other than zero, it will be either a Python int or a Python long...

>>> x.voidField = 123
>>> print repr(x.voidField)
123

And what is the significance of its value?

It's the address pointed to by the void * pointer, i.e. what you'd get from something like...

void* ptr = malloc(1000);
printf("%ld\n", (long) ptr);

다른 팁

C pointers are integers, where the value is the memory address of the thing pointed to. The type of the pointer is basically just a hint for knowing how many bytes to grab when dereferencing.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top