How to create python string from ctype structure?

I use ctypes and I defined this structure to pass parameters

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

Then I call the C function using the following code, but I don't know how to create a string from the structure I 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]

I want to create a python string using the first n bytes of the buffer (the buffer contains NULL characters, but I need to handle this situation and create a string with / 0x00 characters, if necessary). Assignment

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

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

+5
source share
2 answers

, ctypes char, . , ctypes.c_byte ctypes.c_char ctypes.string_at. , :

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", " ")
+3

, C my_struct, C , C . :

import ctypes

BUFSIZE = 10

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

cstr = (ctypes.c_char * BUFSIZE)()
proto = my_struct(cstr)
0

All Articles