ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C++ python混合编程

2021-12-19 21:03:33  阅读:177  来源: 互联网

标签:编程 python py C++ int arr1 array data ptr


  • 配置属性->常规->配置类型为应用程序(.exe)
  • 配置属性->高级->目标文件扩展名为.exe
#include <iostream>
#include <pybind11/embed.h>

namespace py = pybind11;

int main() {
    // start the interpreterand keep it alive
    py::scoped_interpreter guard{};

    auto math = py::module::import("math");
    double root_two = math.attr("sqrt")(2.0).cast<double>();

    std::cout << "The square root of 2 is: " << root_two << "\n";
}

编译成功,运行报错:Fatal Python error: initfsencoding: unable to load the file system codec. ModuleNotFoundError: No module named ‘encodings’
原因在于:需要在用户变量中添加PYTHONHOME和PYTHONPATH两个变量,路径均为python文件夹
链接:链接
C++将python训练的模型导入并预测

#include <iostream>
#include <pybind11/embed.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <vector>
#include <array>
#include <time.h>
namespace py = pybind11;
using namespace std;


//*指针-->numpy 1D
template<typename T>
py::array_t<T> _ptr_to_arrays_1d(T* data, py::ssize_t col) {
    auto result = py::array_t<T>(col);//申请空间
    py::buffer_info buf = result.request();
    T* ptr = (T*)buf.ptr;//获取py::array的指针并隐式转换类型为T*

    for (auto i = 0; i < col; i++)
        ptr[i] = data[i];

    return result;
}


//numpy 1D->interger,如[1]->1
int array_to_int(py::array data) {
    py::buffer_info buf = data.request();
    int* ptr = (int*)buf.ptr;
    return *ptr;
}

//numpy 1D->vector
vector<double> array_to_vector(py::array data,  py::ssize_t col) {
    py::buffer_info buf = data.request();
    double* ptr = (double*)buf.ptr;
    vector<double> res;
    
    for (int i = 0; i < col; i++) {
        res.push_back(ptr[i]);
    }
    return res;
}

//numpy 1D->array
array<double,4> nparray_to_array(py::array data, py::ssize_t col) {
    py::buffer_info buf = data.request();
    double* ptr = (double*)buf.ptr;
    array<double, 4> res;

    for (int i = 0; i < col; i++) {
        res[i] = ptr[i];
    }
    return res;
}

//*指针-->numpy 1D
template<typename T>
py::array_t<T> ptr_to_arrays_1d(T* data, py::ssize_t col) {
    py::array_t<double> out = py::array_t<double>(col);
    auto r3 = out.mutable_unchecked<1>();

    for (int i = 0; i < col; i++)
        r3(i) = data[i];

    return out;
}
//*****测试******//
int main1() {
    py::scoped_interpreter guard{};//python初始化 

    //*测试1D
    double data1[] = { 1.1,2.2,3.3,4.4 };
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data1, 4);
    py::array_t<double> _arr2 = _ptr_to_arrays_1d(data1, 4);
    py::array_t<double> arr1 = ptr_to_arrays_1d(data1, 4);
    py::array_t<double> arr2 = ptr_to_arrays_1d(data1, 4);

    py::print(_arr1);
 
    py::print(_arr2);

    py::array a = _arr1.attr("reshape")(1, -1);
    py::print(a);

    int data2[] = { 1 };
    py::array_t<int> _arr_test = _ptr_to_arrays_1d(data2, 1);
    int res = array_to_int(_arr_test);
    cout << res << endl;
}

int main() {
    // start the interpreterand keep it alive
    py::scoped_interpreter guard{};

    auto math = py::module::import("math");//=import math
    double root_two = math.attr("sqrt")(2.0).cast<double>();//=math.sqrt(2.0)

    std::cout << "The square root of 2 is: " << root_two << "\n";


    auto joblib2 = py::module::import("sklearn.externals").attr("joblib");//=from sklearn.externals import joblib
    auto datasets= py::module::import("sklearn").attr("datasets");//=from sklearn import datasets
    auto numpy = py::module_::import("numpy");//=import numpy
    auto randomForest = py::module::import("sklearn.ensemble").attr("RandomForestClassifier");
    auto rfc2 = joblib2.attr("load")("G:/0/rfc.pkl");//加载模型 =rfc2 = joblib.load('G:/0/rfc.pkl')
  
    py::print(rfc2);
    double data1[] = { 5.1 ,3.5 ,1.4 ,0.2 };
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data1, 4);//[5.1 3.5 1.4 0.2]
    py::array a = _arr1.attr("reshape")(1, -1);//=_attr1.reshape(1,-1),[[5.1 3.5 1.4 0.2]]
    py::print(a);

    auto predict_value = rfc2.attr("predict")(a);//=rfc2.predict(a)
    py::print(predict_value);//[0]
    int res = array_to_int(predict_value);
    cout << res << endl;//0
    
}

//****测试代码运行速度*****//
//numpy 1D->interger 0.193s
//*指针-->numpy 1D 0.175s
int main3() {
    py::scoped_interpreter guard{};
    clock_t start, finish;
    start = clock();
    int T = 10000;
    while (T--) {
        double data1[] = { 5.1 ,3.5 ,1.4 ,0.2 };
        py::array_t<double> _arr1 = _ptr_to_arrays_1d(data1, 4);
        py::array a = _arr1.attr("reshape")(1, -1);
    }
    finish = clock();
    cout << endl << "the time cost is:" << double(finish - start) / CLOCKS_PER_SEC << endl;
}

//****测试vector和numpy互转
int main4() {
    py::scoped_interpreter guard{};
    vector<double> vi = { 1.1,2.2,3.3,4.4 };
    double* data = vi.data();//vector->数组
    cout << *data << endl;
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data, 4);//数组->numpy
    py::print(_arr1);

    vector<double> res = array_to_vector(_arr1, 4);//numpy->vector
    for (auto x : res) {
        cout << x << " ";
    }
}

//****测试array和numpy互转
int main5() {
    py::scoped_interpreter guard{};
    array<double, 4> ar = { 1.1,2.2,3.3,4.4 };
    double* data = ar.data();//array->数组
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data, 4);//数组->numpy
    py::print(_arr1);

    array<double, 4> res = nparray_to_array(_arr1, 4);//numpy->array
    for (auto x : res) {
        cout << x << " ";
    }
}

标签:编程,python,py,C++,int,arr1,array,data,ptr
来源: https://blog.csdn.net/Huichin_Min/article/details/122029836

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有