pybind11使用总结(依赖python3.7版本)

  • 先安装python3.7的源码;
  • test_py.py调用test_cpp中导出函数add()及python三方库:
import os
import pandas as pd
import numpy as np
import libtest as core

def test(a):
    print(pd.__version__)
    print(np.__version__)
    print(core.add(1,2))

  • test_cpp.cpp导出函数并调用test_py.py中函数test()
    #include <Python.h>
    #include <iostream>
    #include "include/pybind11/pybind11.h"
    #include "test_cpp.h"
    
    int add(int i,int j){
         return i+j;
    }
    
    PYBIND11_MODULE(libtest,m){
        m.doc()="pybind11 example";
        m.def("add",&add,"add two number");
    }
    
    extern "c"{
        int todo(){
            pybind11::scoped_interpreter m_python;
            pybind11::object scope=pybind11::module::import("test_py");
            scope.attr("test")(10);
            return 0;
        }
    }
    
    

    test_cpp.h:

extern "C"{
    int todo();
}
  • 编译cmakelist.txt:

 

 linuxBuild.sh:

执行bash linuxBuild.sh编译; 

  • test_cpp_exe.cpp为主进程,调用test_cpp.cpp中test函数:

#ifdef _WIN32
    #include <windows.h>
#else
    #include <dlfcn.h>
#endif
    #include <iostream>

typedef void (* todo)(void);

int main(){
    auto m_gdllhand = dlopen("./test/Ouput/linux/Release/libtest.so",RTLD_NOW|RTLD_GLOBAL);
    if (m_gdllhand==nullptr){
        std::cout << "test..." << std::endl;
        return -1;
    }
    auto m_get_init =  (todo)dlsym(m_gdllhand,"todo");
    m_get_init();
    return 0;
}

编译执行:

g++ test_cpp_exe.cpp -o test_cpp_exe -l test -l dl -L ./ 

最后运行脚本run.sh:

#!/bin/bash

pwd_path=`pwd`
export LD_LIBRARY_PATH=${pwd_path}:$LD_LIBRARY_PATH
./test_cpp_exe

执行结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值