How do I build a python string from a ctype struct?

后端 未结 2 845
不知归路
不知归路 2021-02-06 13:35

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 * BUFS         


        
2条回答
  •  心在旅途
    2021-02-06 14:01

    I think you need to send a pointer to a C string in your my_struct, and not a C string directly, because C strings are null-terminated. Try to do it like this:

    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)
    

提交回复
热议问题