python与C++混合编程实践

1、最简单的操作

新建名为test.cpp的C++代码。

#include<iostream>
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

2、高级操作之一维数组

#include<iostream>
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<iostream>
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

猜你喜欢

转载自blog.csdn.net/wuxulong123/article/details/129291062