Chinmay Kanchi的答案很好,但是我想要一个传递和返回变量/数组到C ++代码的函数示例。我会在这里包括它,以防它对其他人有用。
传递并返回整数
该函数的C ++代码采用整数并将其加到返回值中,
extern "C" int add_one(int i)
{
return i+1;
}
另存为文件test.cpp
,注意所需的 extern“ C”(对于C代码可以删除)。这是使用g ++编译的,其参数类似于Chinmay Kanchi的答案,
g++ -shared -o testlib.so -fPIC test.cpp
Python代码使用load_library
从numpy.ctypeslib
假定路径到与Python脚本位于同一目录中的共享库,
import numpy.ctypeslib as ctl
import ctypes
libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)
py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)
这将按预期打印6。
传递并打印数组
您还可以按以下方式传递数组,以使C代码可以打印数组的元素,
extern "C" void print_array(double* array, int N)
{
for (int i=0; i<N; i++)
cout << i << " " << array[i] << endl;
}
与以前一样编译,并以相同方式导入。然后,使用该功能的额外Python代码将是,
import numpy as np
py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64,
flags='aligned, c_contiguous'),
ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)
在这里我们指定数组,第一个参数print_array
,作为指针对齐,c_contiguous 64个浮点的numpy的阵列,第二个参数为一个整数,它告诉C代码numpy的数组中的元素数目。然后通过C代码如下打印,
1.4
2.6
3.0
>>>
在importtest.py中有吗?人们发布>>>
每行都有的代码时,表示该代码正在交互式外壳程序中运行。要从文件中运行它,请删除>>>
它出现的位置(即3>符号和一个空格)。