您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python使用ctypes传递char *数组并填充结果

Python使用ctypes传递char *数组并填充结果

以下代码有效:

test.py:

import ctypes
lib = ctypes.CDLL("./libtest.so")
string_buffers = [ctypes.create_string_buffer(8) for i in range(4)]
pointers = (ctypes.c_char_P*4)(*map(ctypes.addressof, string_buffers))
lib.test(pointers)
results = [s.value for s in string_buffers]
print results

test.c(使用编译为libtest.so gcc test.c -o libtest.so -shared -fPIC):

#include <string.h>
void test(char **strings) {
    strcpy(strings[0],"this");
    strcpy(strings[1],"is");
    strcpy(strings[2],"a");
    strcpy(strings[3],"test!");
}

正如Aya所说,您应该确保终止零的空间。但是我认为您的主要问题是字符串缓冲区是垃圾回收或类似的东西,因为现在不再直接引用它了。否则,如果没有为字符串缓冲区存储任何引用,则在字符串缓冲区的创建过程中会引起其他麻烦。例如,这导致相同地址而不是不同地址的四倍:

import ctypes
pointers = [ctypes.addressof(ctypes.create_string_buffer(8)) for i in range(4)]
print pointers
python 2022/1/1 18:42:34 有287人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶