新建名为test.cpp的C++代码。
#include
using namespace std;
extern "C"
{
int func(int a,int b)
{
cout<<a<<"::"<<b<<endl;
return a+b;
}
}
linux下命令行输入一下命令进行编译
g++ test.cpp -fPIC -shared -o test.so
新建名为test.py的python程序
import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./test.so")
d = lib.func(3,4)
print("Python:",d)
运行可得
3::4
Python: 7
#include
using namespace std;
extern "C"
{
int func(int a[], int b)
{
int c=0;
for(int i=0;i< b;i++)
{
cout<<a[i]<<";"<<endl;
c += a[i];
}
return c;
}
}
import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./test.so")
import numpy as np
length = 4
a = (ctypes.c_int*length)(*tuple([1,2,3,4]))
d = lib.func(a, length)
print("Python:",d)
输出结果如下
1;
2;
3;
4;
Python: 10
import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./test.so")
import numpy as np
length = 4
a = (ctypes.c_int*length)(*tuple([1,2,3]))
d = lib.func(a, length)
print("Python:",d)
输出结果如下
1;
2;
3;
0;
Python: 6
可以看出,当数组的初始值不够初始化数组时,默认为0。
3、二维数组
#include
using namespace std;
extern "C"
{
int func(int a[4][3]){
int c=0;
for(int i=0;i<4;i++)
{
for (int j=0;j<3;j++)
{
cout<<a[i][j]<<";"<<endl;
c += a[i][j];
}
}
return c;
}
}
import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./test.so")
import numpy as np
b= [tuple(list(arr)) for arr in np.array([[1,2,5,4],[4,5,6,7],[1,2,3,4]])]
c = ((ctypes.c_int*4)*3)(*tuple(b))
d = lib.func(c)
print("Python:",d)
上面这种情况目的在于联合numpy数组进行编程
1;
2;
5;
4;
4;
5;
6;
7;
1;
2;
3;
4;
Python: 44