Python and C++ mixed programming practice

1. The simplest operation

Create a new C++ code named test.cpp.

#include<iostream>
using namespace std;
extern "C"
{
    
    
    int func(int a,int b)
    {
    
    
        cout<<a<<"::"<<b<<endl;
        return a+b;
    }
}

Enter the command on the command line under linux to compile

g++ test.cpp -fPIC -shared -o test.so

Create a new python program named test.py

import ctypes
ll = ctypes.cdll.LoadLibrary
lib = ll("./test.so")
d = lib.func(3,4)
print("Python:",d)

Available for operation

3::4
Python: 7

2. Advanced operations on one-dimensional arrays

#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)

The output is as follows

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)

The output is as follows

1;
2;
3;
0;
Python: 6

It can be seen that when the initial value of the array is not enough to initialize the array, the default is 0.
3. Two-dimensional array

#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)

The purpose of the above situation is to combine numpy arrays for programming

1;
2;
5;
4;
4;
5;
6;
7;
1;
2;
3;
4;
Python: 44

Guess you like

Origin blog.csdn.net/wuxulong123/article/details/129291062