- 先安装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
执行结果: