如何使用 ctypes 访问指向内部对象的 typedef 结构指针?

How do I access a typedef struct pointer to an internal object with ctypes?

我在 Python 3.6 中使用 ctypes 来连接 C 库。其中一个函数启用库和 returns 类型定义到需要传递给后续函数调用的内部对象。这是一个例子:

// Type definition of the internal object.
typedef struct lib_internal_obj * lib_internal_obj_t;

/**
 * Struct containing the available options for the library
 */
struct lib_options {
        char ip[255];         
        int bufsize_MB;    
};

/** Constructor of a lib object.
 * \return A newly created lib object or NULL if construction failed
 */
extern lib_internal_obj_t    lib_internal_obj_new(struct lib_options * options); 


/**
 * Example of how the internal object is used. 
 *
 */
extern int     lib_get_options(lib_internal_obj_t obj, struct lib_options *options);

/**
 * Destructor of the lib object.
 */
extern void    lib_del(lib_internal_obj_t *obj);

我不知道这个对象是如何被 returned 并用 ctypes 存储在 Python 中的。我假设它像 Python 中的正常函数调用一样工作。这是我尝试过的:

import ctypes as c

class LIB_OPTIONS(c.Structure):
    """Struct containing the available options for the library"""
    _fields_ = [
        ('ip', c.c_char * 255),
        ('bufsize_MB', c.c_int)
    ]

# Open C lib
c_lib = c.CDLL('./path/to/lib/lib.so', mode=1)

# Set options
lib_opts = LIB_OPTIONS()
lib_opts.ip = "192.168.1.1".encode('utf-8')
lib_opts.bufsize_MB = 2

# Not sure how to handle this
lib_object = c_lib.lib_internal_obj_new(c.byref(lib_opts))

当我 运行 出现以下错误时:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

我很确定这与 clib.lib_internal_obj_new 调用有关。有没有办法 return typedef 结构并从 ctypes 中正确存储它。非常感谢任何帮助。

ctypes 出现问题的通常原因是没有为被调用的函数定义 .argtypes.restype。特别是,return 类型默认为 c_int(通常为 32 位),在 64 位系统上,您的函数将 return 为 64 位指针。

import ctypes as c

class LIB_OPTIONS(c.Structure):
    """Struct containing the available options for the library"""
    _fields_ = [('ip', c.c_char * 255),
                ('bufsize_MB', c.c_int)]

c_lib = c.CDLL('./test')
c_lib.lib_internal_obj_new.argtypes = c.POINTER(LIB_OPTIONS), # 1-tuple declaring input parameter
c_lib.lib_internal_obj_new.restype = c.c_void_p # generic pointer

lib_opts = LIB_OPTIONS(b'192.168.1.1',2)
lib_object = c_lib.lib_internal_obj_new(c.byref(lib_opts))