- 下载g++,链接
- 下载后解压,添加环境变量
添加环境变量
我的电脑->属性->高级系统设置->环境变量->系统变量
系统变量->Path->编辑->新建->D:\mingw64\bin->确定
系统变量->新建->变量名:LIBRARY_path->变量值:D:\mingw64\lib->确定
系统变量->新建->变量名:C_INCLUDE_PATH->变量值:D:\mingw64\include->确定 - 检测g++是否可以正常运行
在cmd输入g++ -v,若正常运行则完成。 - 测试代码
单独的函数直接在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();
}
}
- 打开命令行,进入到main.cpp所在目录,生成链接库
g++ -o libpycallcpp.so -shared -fPIC main.cpp -m64
- python文件测试
import ctypes
dll = ctypes.cdll.LoadLibrary
lib = dll('E:/Robert/predict_c++/codeblock/demo/libpycallcpp.so')
lib.my_print()
lib.get_print()
- 传递数组并获取返回值
#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]
- 参考链接:
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