使用ctypes从Python调用带有Char **参数的C方法 [英] Calling C methods with Char** arguments from Python with ctypes
问题描述
我需要一种方法,可以使用ctypes库将数组从Python传递给char *到C库.
I need a way to pass an array to char* from Python using ctypes library to a C library.
我尝试过的某些方法导致我出现了细分错误,而另一些导致了垃圾信息.
Some ways I've tried lead me to segmentation faults, others to rubbish info.
推荐答案
在这个问题上苦苦挣扎了一段时间之后,我决定写一个小的HowTo,以便其他人可以从中受益.
As I've been struggling with this issue for some time, I've decided to write a small HowTo so other people can benefit.
具有这段C代码:
void passPointerArray(int size, char **stringArray) {
for (int counter=0; counter < size; counter++) {
printf("String number %d is : %s\n", counter, stringArray[counter]);
}
}
我们想使用ctypes从python调用它(有关ctypes的更多信息可以在上一篇文章中找到),因此我们写下以下代码:
We want to call it from python using ctypes (more info about ctypes can be found in a previous post), so we write down the following code:
def pass_pointer_array():
string_set = [
"Hello",
"Bye Bye",
"How do you do"
]
string_length = len(string_set)
select_type = (c_char_p * string_length)
select = select_type()
for key, item in enumerate(string_set):
select[key] = item
library.passPointerArray.argtypes = [c_int, select_type]
library.passPointerArray(string_length, select)
现在,我阅读它似乎非常简单,但是我很高兴找到合适的类型传递给ctype以避免分段错误...
Now that I read it it appears to be very simple, but I enjoyed a lot finding the proper type to pass to ctypes in order to avoid segmentation faults...
这篇关于使用ctypes从Python调用带有Char **参数的C方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!