我有一个简单的 C++ 文件,我想通过 C 扩展将其导出到 Python 中。我编译 .cc 文件并创建一个共享库,然后使用 ctypes 中的 CDLL 在 Python 中调用该共享库。但是,当我调用库函数时,我很难正确传递 Python 列表,并且它无法正确返回。我哪里错了?
// test.cc
extern "C" {
int call_my_routine(int *array) {
int i;
int count = 0;
for(i=0; array[i]!='\0'; i++)
{
count++;
}
return count;
}
}
// test.py
from ctypes import CDLL, c_int
so_file = "./libtest.so"
my_function = CDLL(so_file)
py_list = [2,3,5,7,4,12,21,49]
array = (c_int * len(py_list))(*py_list)
print(my_function.call_my_routine(array))
正确的输出应该是 8,但实际返回的是 17。
我用
编译共享库g++ -I ./inc -fpic -c test.cc -o test.o
g++ -shared -o libtest.so test.o
声明,我不是 C 程序员。
您在代码中面临的问题源于您如何尝试确定 C++ 函数中从 Python 传递的数组的长度。与 C 样式字符串不同,整数数组没有空终止字符,因此当前检查
'\0'
来查找数组末尾的方法将无法正常工作。
这是代码的更正版本:
// test.cc
extern "C" {
int call_my_routine(int *array, int length) {
int count = 0;
for (int i = 0; i < length; i++) {
count++;
}
return count;
}
}
# test.py
from ctypes import CDLL, c_int
so_file = "./libtest.so"
my_function = CDLL(so_file)
py_list = [2, 3, 5, 7, 4, 12, 21, 49]
array = (c_int * len(py_list))(*py_list)
print(my_function.call_my_routine(array, len(py_list)))
在更正后的代码中,C++ 函数
call_my_routine
现在接受两个参数:整数数组及其长度。数组的长度是使用 len(py_list)
函数从 Python 显式传递的。这种方法可确保将长度准确地提供给 C++ 函数,从而在计算元素时得到正确的结果。
当您使用此更正后的代码运行 Python 脚本时,它应该输出预期结果 8。