ctypes中的LP_ *指针和* _p指针有什么区别? (以及与结构的怪异互动) [英] What's the difference between LP_* pointers and *_p pointers in ctypes? (and weird interaction with structs)

查看:272
本文介绍了ctypes中的LP_ *指针和* _p指针有什么区别? (以及与结构的怪异互动)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解Python ctypes中的LP _ *(例如LP_c_char)和* _p(例如c_char_p)指针之间的区别。有文件可以区分它们吗?

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?

我对* _p指针的了解很少,表明它们更好(以某种未指定的方式),但是当我尝试使用时他们作为结构域,我得到奇怪的行为。例如,我可以使用LP_c_char指针字段创建一个结构:

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:

import 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)

指针是:

<class 'ctypes.LP_c_char'> 

但是当我使用c_char_p指针字段创建结构时:

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)

生成的 ptr字段为

<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


表示C char *数据类型当它指向以零结尾的字符串时。对于也可能指向二进制数据的通用字符指针,必须使用POINTER(c_char)。

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 映射到Python的 str 类型,因为它假定您要引用的是字符串,通常使用<$时就是这种情况C中的c $ c> char * 。 LP_c_char 没有这样的假设。

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.


基本数据类型在作为外部函数调用结果返回时,或例如通过检索结构字段成员或数组项而返回时,将透明地转换为本机Python类型。换句话说,如果外部函数的重设类型为c_char_p,您将始终收到一个Python字符串,而不是c_char_p实例。

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.

这篇关于ctypes中的LP_ *指针和* _p指针有什么区别? (以及与结构的怪异互动)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆