问题
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.
回答1:
As I've been struggling with this issue for some time, I've decided to write a small HowTo so other people can benefit.
Having this C piece of code:
void passPointerArray(int size, char **stringArray) {
for (int counter=0; counter < size; counter++) {
printf("String number %d is : %s\n", counter, stringArray[counter]);
}
}
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)
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...
来源:https://stackoverflow.com/questions/19136347/calling-c-methods-with-char-arguments-from-python-with-ctypes