What's the difference between LP_* pointers and *_p pointers in ctypes? (and weird interaction with structs)
I'm having trouble understanding the difference between LP_* (e.g. LP_c_char) and *_p (e.g. c_char_p) pointers in Python ctypes. Is there documentation distinguishing them?
The little I've read about *_p pointers suggests that they're better (in some unspecified way), but when I try to use them as struct fields, I get weird behavior. For example, I can create a struct with an LP_c_char pointer field:
imp开发者_如何学Pythonort ctypes
char = ctypes.c_char('a')
class LP_Struct(ctypes.Structure):
_fields_ = [('ptr', ctypes.POINTER(ctypes.c_char))]
struct = LP_Struct(ctypes.pointer(char))
print type(struct.ptr)
And the resulting pointer is:
<class 'ctypes.LP_c_char'>
But when I create a struct with a c_char_p pointer field:
class Struct_p(ctypes.Structure):
_fields_ = [('ptr', ctypes.c_char_p)]
p = ctypes.pointer(char)
struct = Struct_p(ctypes.cast(p, ctypes.c_char_p))
print type(struct.ptr)
the resulting "ptr" field is
<type 'str'>
In other words, the pointer has been dereferenced somewhere in the process.
http://docs.python.org/library/ctypes.html#ctypes.c_char_p
Represents the C char * datatype when it points to a zero-terminated string. For a general character pointer that may also point to binary data, POINTER(c_char) must be used.
c_char_p
is mapped to Python's str
type because it's assuming you're referring to a string, which is generally the case when you're using char *
in C. LP_c_char
makes no such assumption.
Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types. In other words, if a foreign function has a restype of c_char_p, you will always receive a Python string, not a c_char_p instance.
精彩评论