我试图将两个字符串数组从python传递到C,在嵌套的for循环中使用它们,并将它们与参数进行比较,如果两个字符串满足此参数,我会将它们附加到C中的新字符串数组中。最后,我返回了比较字符串的新数组。使用CDLL在python中调用此函数,并且使用的新字符串数组是我的python脚本。
#In Python:
PyOne = ["Apple", "Orange", "Banana"]
PyTwo = ["Cucumber", "Mango", "Pineapple", "Apple"]
我已经将它们翻译为在C函数中使用,如下所示:
#In Python:
PyOne = ["Apple", "Orange", "Banana"]
PyOne_bytes = []
for i in range(len(PyOne)):
PyOne_bytes.append(bytes(PyOne[i], 'utf-8'))
One_array = (ctypes.c_char_p * (len(PyOne_bytes)+1))()
One_array[:-1] = PyOne_bytes
PyTwo = ["Cucumber", "Mango", "Pineapple", "Apple"]
PyTwo_bytes = []
for i in range(len(PyTwo)):
PyTwo_bytes(bytes(PyTwo[i], 'utf-8'))
Two_array = (ctypes.c_char_p * (len(PyTwo_bytes)+1))()
Two_array[:-1] = PyTwo_bytes
上面的代码将现有的Python字符串数组转换为C可以解释的数组。
这是我的C函数:
// In C
#include
#include
#include
#define SCALING_FACTOR 0.1
#include
...
char ** mainForLoop(const char ** PyOne, const char ** PyTwo) {
char ** matches = malloc(100 * sizeof(char*));
size_t i = 0;
size_t j = 0;
for (i = 0; i < sizeof(PyOne)/sizeof(PyOne[0]); i++) {
for (j = 0; j < sizeof(PyTwo)/sizeof(PyTwo[0]); j++) {
double v = comparison(PyOne[i], PyTwo[i]);
if (v > 4) {
strcat(matches, (PyOne[i]));
strcat(matches, (";"));
}
}
}
return matches;
}
在python中,然后按如下所示打印从函数返回的值:
c.mainForLoop.argtypes = [POINTER(c_char_p), POINTER(c_char_p)]
c.mainForLoop.restype = ctypes.c_char_p
print(c.mainForLoop(One_array, Two_array))
例如,如果compare(“ Apple”,“ Cucumber”)= 5(即> 4),comparison(“ Orange”,“ Mango”)= 7(即> 4),并且所有其他compare()<4然后由于以下原因,我希望...
// In C
double v = comparison(PyOne[i], PyTwo[i]);
if (v > 4) {
strcat(matches, (PyOne[i]));
strcat(matches, (";"));
}
对于
#In Python
print(cDoc.mainForLoop(One_array, Two_array))
>>> b'Apple;Orange'
但目前,此打印:
>>> b'Apple;'
我不知道自己在代码中做错了什么。我是C的新手,我已经尽力想尽一切办法,任何帮助将不胜感激,一个解释也将是王牌!
谢谢!