Python 初始化ctypes字符串对象
虽然我一直在读一些关于类似主题的问题,但我不知道我的情况有什么意义。。。我的库标题中定义了一个C结构,如下所示:Python 初始化ctypes字符串对象,python,casting,ctypes,Python,Casting,Ctypes,虽然我一直在读一些关于类似主题的问题,但我不知道我的情况有什么意义。。。我的库标题中定义了一个C结构,如下所示: #define CLT_MAX_SIZE 16 #define MSG_MAX_SIZE 512 typedef struct { LOG_LEVEL m_level; char m_text[MSG_MAX_SIZE]; char m_client[CLT_MAX_SIZE];
#define CLT_MAX_SIZE 16
#define MSG_MAX_SIZE 512
typedef struct
{
LOG_LEVEL m_level;
char m_text[MSG_MAX_SIZE];
char m_client[CLT_MAX_SIZE];
} LOG_Msg;
在为此库编写Python包装时,我遇到了处理此结构的问题:
class Message(Structure):
""" """
_fields_ = [
("m_level", c_int),
("m_text", c_char_p*MSG_MAX_SIZE),
("m_client", c_char_p*CLT_MAX_SIZE)
]
问题是我无法为此类编写正确的init方法。我希望它与以下原型相关:
def __init__(self, level, client, text):
""" """
self.m_level = c_int(level)
self.m_text = **???**
self.m_client = **???**
我曾尝试使用ctypes cast()和create_string_buffer()方法,但尚未成功初始化这两个文本字段。一定是在什么地方漏掉了什么,但不知道有多远
欢迎提供任何提示;) 您想要的是:
#!/usr/bin/python
from ctypes import *
class Message(Structure):
MSG_MAX_SIZE=128
CLT_MAX_SIZE=64
_fields_ = [
("m_level", c_int),
("m_text", type(create_string_buffer(MSG_MAX_SIZE))),
("m_client", type(create_string_buffer(CLT_MAX_SIZE)))
]
print Message.m_text
print Message.m_client
t = Message(100, 'abcdef' ,'flurp')
print t
print t.m_text
打印Message.m_文本和Message.m_客户端时,您将看到它们是正确的类型:
<Field type=c_char_Array_128, ofs=4, size=128>
<Field type=c_char_Array_64, ofs=132, size=64>
但是,您可以创建对象并将字段用作具有边界限制的普通Python字符串。
create\u string\u buffer
是一个方便的排序函数。但是仅仅为了获取类型而分配缓冲区并没有多大意义。使用c_char*MSG_MAX_SIZE
创建数组类型。感谢您的提示,这正是缺少的!