如何建立从CTYPE结构一个Python字符串? [英] How do I build a python string from a ctype struct?

查看:887
本文介绍了如何建立从CTYPE结构一个Python字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的ctypes和我定义这个结构,以传递参数

I'm using ctypes and I've defined this struct in order to pass parameters

class my_struct(ctypes.Structure):
    _fields_ = [ ("buffer", ctypes.c_char * BUFSIZE),
                 ("size", ctypes.c_int )]

然后我打电话用下面的code中的C函数,但我不知道如何创建从我创建了结构的字符串。

Then I call the C function using the following code, but I don't know how to create a string from the struct I've created.

class Client():

    def __init__(self):
        self.__proto = my_struct()
        self.client = ctypes.cdll.LoadLibrary(r"I:\bin\client.dll")

    def version(self):
        ret = self.client.execute(ctypes.byref(self.__proto))
        my_string = self.__proto.buffer[:self.__proto.size]

我想用的缓冲区的前n个字节(缓冲区包含NULL字符,但我必须处理这种情况和/ 0×00字符,如果necesary创建的字符串)创建一个Python字符串。该asignation

I want to create a python string using the first n bytes of the buffer (the buffer contains NULL characters but I have to handle this situation and create the string with /0x00 characters if necesary). The asignation

my_string = self.__proto.buffer[:self.__proto.size]

不工作bacause截断字符串,如果为0x00出现。任何想法是值得欢迎的。先谢谢了。

is not working bacause truncates the string if 0x00 appears. Any idea is welcome. Thanks in advance.

推荐答案

您的问题是, ctypes的试图做一些魔法为你字符阵列,自动转换成他们NUL结尾的字符串。您可以通过使用解决这个神奇的 ctypes.c_byte 类型,而不是 ctypes.c_char 并检索值作为字符串 ctypes.string_at 。您可以访问该成员更好一点与结构类的帮助属性,如:

Your problem is that ctypes tries to do some magic for you with char arrays, auto-converting them into NUL-terminated strings. You can get around this magic by using the ctypes.c_byte type instead of ctypes.c_char and retrieving the value as a string with ctypes.string_at. You can make accessing the member a little nicer with a helper property on the structure class, such as:

import ctypes
BUFSIZE = 1024

class my_struct(ctypes.Structure):
    _fields_ = [ ("_buffer", ctypes.c_byte * BUFSIZE),
                 ("size", ctypes.c_int )]

    def buffer():
        def fget(self):
            return ctypes.string_at(self._buffer, self.size)
        def fset(self, value):
            size = len(value)
            if size > BUFSIZE:
                raise ValueError("value %s too large for buffer",
                                 repr(value))
            self.size = size
            ctypes.memmove(self._buffer, value, size)
        return property(fget, fset)
    buffer = buffer()

proto = my_struct()
proto.buffer = "here\0are\0some\0NULs"
print proto.buffer.replace("\0", " ")

这篇关于如何建立从CTYPE结构一个Python字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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