如果可以取依赖,可以使用boost::python来帮忙。
下面有一个完整的工作示例应用程序,它仅链接 boost_python 和 python2.7 共享库。 -O3 构建只有 51K。
导入 python 模块:
您使用boost::python::exec 执行导入语句,将您的python 模块导入boost::python::object
bp::object import(const std::string& module, const std::string& path)
{
bp::object globals = bp::import("__main__").attr("__dict__");
bp::dict locals;
locals["module_name"] = module;
locals["path"] = path;
// execute some python code which imports the file
bp::exec("import imp\n"
"new_module = imp.load_module(module_name, open(path), path, ('bp', 'U', imp.PY_SOURCE))\n",
globals,
locals);
return locals["new_module"];
}
// get an object containing the contents of the file "test.py"
bp::object module = import("test", "test.py");
获取python模块中元素的句柄:
// get a handle to something declared inside "test.py"
bp::object Script = module.attr("Script");
实例化一个对象:
// Instantiate a script object
bp::object script = Script();
调用Script的成员函数:
// calls Script.run(), passing no arguments
script.attr("run")();
您还可以将 C++ 代码公开给 python:
使用 boost::python::class 向刚刚导入的模块公开一个 C++ 类:
struct Foo
{
void func();
}
bp::object FooWrapper(
bp::class_<Foo>("Foo")
.def("func", &Foo::func)
);
bp::object foo = FooWrapper(); // instantiate a python wrapped Foo object
bp::object script = Script(foo); // create a Script instance, passing foo
工作示例:
test.py
class Script(object):
def __init__(self, ifc):
print 'created script'
self.ifc = ifc
def run(self):
print 'running'
self.ifc.execute(5)
def result(self, i):
print 'result={}'.format(i)
main.cpp
#include <boost/python.hpp>
namespace bp = boost::python;
bp::object import(const std::string& module, const std::string& path)
{
bp::object globals = bp::import("__main__").attr("__dict__");
bp::dict locals;
locals["module_name"] = module;
locals["path"] = path;
bp::exec("import imp\n"
"new_module = imp.load_module(module_name, open(path), path, ('bp', 'U', imp.PY_SOURCE))\n",
globals,
locals);
return locals["new_module"];
}
///////////////////////////
class Runner
{
public:
void init(bp::object script)
{
// capture methods at creation time so we don't have to look them up every time we call them
_run = script.attr("run");
_result = script.attr("result");
}
void run()
{
_run(); // call the script's run method
}
void execute(int i) // this function is called by the python script
{
_result(i * 2); // call the script's result method
}
bp::object _run;
bp::object _result;
};
int main()
{
Py_Initialize();
// load our python script and extract the Script class
bp::object module = import("test", "test.py");
bp::object Script = module.attr("Script");
// wrap Runner and expose some functions to python
bp::object RunnerWrapper(
bp::class_<Runner>("Runner")
.def("execute", &Runner::execute)
);
// create a python wrapped instance of Runner, which we will pass to the script so it can call back through it
bp::object wrapper = RunnerWrapper();
bp::object script = Script(wrapper);
// extract the runner instance from the python wrapped instance
Runner& runner = bp::extract<Runner&>(wrapper);
// initialise with the script, so we can get handles to the script's methods we require
runner.init(script);
runner.run();
Py_Finalize();
return 0;
CMakeLists.txt
cmake_minimum_required (VERSION 3.2.2)
find_package(Boost COMPONENTS python REQUIRED)
find_package(PythonLibs 2.7 REQUIRED)
add_executable (py_embed main.cpp)
target_link_libraries (py_embed ${Boost_PYTHON_LIBRARY} ${PYTHON_LIBRARIES})
target_include_directories(py_embed SYSTEM PRIVATE ${PYTHON_INCLUDE_DIRS})
可下载源代码here