【发布时间】:2019-05-16 03:38:54
【问题描述】:
我定义了一个简单的 C 结构体 TestStruct 和一个函数 init_struct 来创建一个实例并返回一个指向它的指针
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int x;
int y;
char* msg;
} TestStruct;
TestStruct* init_struct(int x, int y, char* msg) {
TestStruct* p;
TestStruct initial = {x, y, msg};
p = malloc(sizeof(TestStruct));
*p = initial;
return p;
}
我使用gcc 将C 代码编译成.so 文件。然后,在 Python 中,我想使用 ctypes 创建一个绑定,它可以访问 C 结构的所有成员
import ctypes
import os
class PyStruct(ctypes.Structure):
_fields_ = [('x', ctypes.c_int),
('y', ctypes.c_int),
('msg', ctypes.c_char_p)]
lib = ctypes.cdll.LoadLibrary(os.path.abspath('/path/to/libstruct.so'))
_init_struct = lib.init_struct
_init_struct.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p]
_init_struct.restype = ctypes.POINTER(PyStruct)
myStruct = _init_struct(1, 4, ctypes.c_char_p(b'hello world'))
print(myStruct.contents.x, myStruct.contents.y, myStruct.contents.msg)
结构的整数成员(x 和y)打印得很好,但我不知道如何打印msg 指向的字符串。我最终看到的不是预期的hello world,而是一个字节字符串b'\x01。我从其他阅读中得到的预感是,我正在截断真实的、更长的字符串,并且只显示第一个字节。
【问题讨论】:
-
也许您需要从字节流转换为字符串?
-
仅供参考,您可以直接传递
b'hello world'而无需ctypes.c_char_p(b'hello world')包装。 -
关于:
p = malloc(sizeof(TestStruct)); *p = initial;1) 应始终检查 (!=NULL) 返回值以确保mallloc成功。 2)第二条语句不会复制initial. Suggest using:strncpy(p, &initial, sizeof(TestStruct));`的内容
标签: python c struct binding ctypes