python调用c++函数与类

  1. 下载g++,链接
  2. 下载后解压,添加环境变量
    添加环境变量
    我的电脑->属性->高级系统设置->环境变量->系统变量
    系统变量->Path->编辑->新建->D:\mingw64\bin->确定
    系统变量->新建->变量名:LIBRARY_path->变量值:D:\mingw64\lib->确定
    系统变量->新建->变量名:C_INCLUDE_PATH->变量值:D:\mingw64\include->确定
  3. 检测g++是否可以正常运行
    在cmd输入g++ -v,若正常运行则完成。
  4. 测试代码
    单独的函数直接在extern "C"里定义;类或对象则先在外部定义,再在extern "C"里实例化
#include<iostream>
#include<cmath>
using namespace std;

class Distance {
public:
    void test_print();
};
void Distance::test_print()
{
    cout << "456" <<endl;
}
extern "C" {
	Distance obj;
	void my_print()
    {
    cout << "123" <<endl;
    }
	void get_print()
	{
	    obj.test_print();
	}

}
  1. 打开命令行,进入到main.cpp所在目录,生成链接库
g++ -o libpycallcpp.so -shared -fPIC main.cpp -m64
  1. python文件测试
import ctypes

dll = ctypes.cdll.LoadLibrary
lib = dll('E:/Robert/predict_c++/codeblock/demo/libpycallcpp.so')
lib.my_print()
lib.get_print()
  1. 传递数组并获取返回值
#include<iostream>
#include<cmath>

using namespace std;

extern "C" {
	void test_print()
    {
        cout << "load finish!" <<endl;
    }

	void hehe(double* d, double* a,double* b,int rows,int cols){
        double result;
        int row,col;
        for(row = 0;row < rows; row++)
        {
            result = 0;
            for(col = 0;col < cols; col++)
            {
                int ind = row * cols + col;
                cout << a[col] << "|" << b[ind] <<endl;
                result += (a[col] - b[ind]) * (a[col] - b[ind]);
            }
            d[row] = sqrt(result);
        }
    }
}
import ctypes
import numpy as np

dll = ctypes.cdll.LoadLibrary
lib = dll('E:/Robert/predict_c++/codeblock/demo/libpycallcpp.so')
lib.test_print()

distance = np.zeros(3, dtype=np.float)
distance_1 = distance.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
a = np.array([1, 2, 3], dtype=np.float)
a_1 = a.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
b = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]], dtype=np.float)
b_1 = b.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
lib.hehe(distance_1, a_1, b_1, 3, 3)
print(distance)

可得结果

load finish!
1|1
2|2
3|3
1|2
2|3
3|4
1|3
2|4
3|5
[0.         1.73205081 3.46410162]
  1. 参考链接:
    https://blog.csdn.net/weixin_40313940/article/details/109515357
    https://blog.csdn.net/zong596568821xp/article/details/81133511
    https://blog.csdn.net/leviopku/article/details/83824625
    https://blog.csdn.net/qq_25105061/article/details/112173430
    https://zhuanlan.zhihu.com/p/39098612
    https://blog.csdn.net/springlustre/article/details/101177282
    https://blog.csdn.net/flyztek/article/details/73612469
    https://www.cnblogs.com/dpf-learn/p/6207546.html
    https://www.cnblogs.com/qniguoym/p/7690675.html
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值