bit*_*wit 9 c c++ python ctypes
我正在尝试使用ctypes在python中创建一个char*数组,以传递给库以填充字符串.我期待4个字符串的长度不超过7个字符.
我的py代码看起来像这样
testlib.py
from ctypes import *
primesmile = CDLL("/primesmile/lib.so")
getAllNodeNames = primesmile.getAllNodeNames
getAllNodeNames.argtypes = [POINTER(c_char_p)]
results = (c_char_p * 4)(addressof(create_string_buffer(7)))
err = getAllNodeNames(results)
Run Code Online (Sandbox Code Playgroud)
lib.cpp
void getAllNodeNames(char **array){
DSL_idArray nodes; //this object returns const char * when iterated over
network.GetAllNodeIds(nodes);
for(int i = 0; i < (nodes.NumItems()); i++){
strcpy(array[i],nodes[i]);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行此代码时,我不断收到分段错误.我已经从C创建了一个完美的测试,但在Python中,我必须正确地设置指针数组或其他东西.它似乎到达循环中的第二个节点,然后出现问题,因为我已经看到将数据吐出到命令行.任何见解都会非常感激.
Flo*_*iem 10
以下代码有效:
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
Run Code Online (Sandbox Code Playgroud)
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!");
}
Run Code Online (Sandbox Code Playgroud)
正如Aya所说,你应该确保终止零的空间.但我认为你的主要问题是字符串缓冲区是垃圾收集或类似的东西,因为没有直接引用它.或者在没有为它们存储引用时,在字符串缓冲区的创建过程中导致其他问题.例如,这导致相同地址的四倍而不是不同的地址:
import ctypes
pointers = [ctypes.addressof(ctypes.create_string_buffer(8)) for i in range(4)]
print pointers
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17522 次 |
| 最近记录: |