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

Python使用ctypes传递char *数组并填充结果,第1张

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

以下代码有效:

test.py:

import ctypeslib = 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 ctypespointers = [ctypes.addressof(ctypes.create_string_buffer(8)) for i in range(4)]print pointers


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4980150.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存