Boost-python封装Cpp代码供Python调用
Boost.Python是连接C++与Python的成熟桥梁工具,通过封装函数和类可生成Python可调用模块,实现双向交互。它支持重载、默认参数和继承等特性,使开发高效。封装过程看似简单,但需注意类型转换、异常处理、内存管理等常见陷阱,避免运行时错误,确保程序稳定。
在Python中调用C++代码时,Boost.Python是一个非常成熟的桥梁工具。下面通过几个简单的示例,展示如何将C++函数和类封装成Python可调用的模块。这些示例本身不难,但对于第一次接触的朋友来说,有些细节确实容易踩坑,值得逐一拆开看看。

封装一个单一的函数
#include
#include
#include
#include
#include
using namespace boost::python;
using namespace std;
void HelloWorld()
{
cout << "HelloWorld!" << endl;
}
BOOST_PYTHON_MODULE(CToPython)
{
def("hello", HelloWorld, "Print HelloWorld!");
}
带参数的单一函数
void HelloWorld(string out, string put)
{
cout << out + put << endl;
}
BOOST_PYTHON_MODULE(CToPython)
{
def("hello", HelloWorld, args("x", "y"), "Print HelloWorld!");
}
注意:BOOST_PYTHON_MODULE(...) 中的名称必须和工程项目名称保持一致。而 args 参数的作用,是将 C++ 函数形参的名字映射到 Python 函数的形参名。举个例子,C++ 函数 HelloWorld(string out, string put) 经过映射后,在 Python 中调用时实际使用的是 hello(x, y)。
封装一个类
#include
#include
#include
#include
#include
#include
using namespace boost::python;
using namespace std;
class helloworld
{
public:
string name;
string talk;
public:
helloworld()
{
name = "hua";
talk = "HelloWorld!";
}
helloworld(string n, string t)
{
name = n;
talk = t;
}
void set_name(string n) { name = n; }
void set_talk(string t) { talk = t; }
string get_name() { return name; }
string get_talk() { return talk; }
};
BOOST_PYTHON_MODULE(CToPython)
{
class_("helloworld", init<>())
.def(init())
.def_readonly("name", &helloworld::name)
// .def_readwrite("name", &helloworld::name)
.def_readwrite("talk", &helloworld::talk)
.def("set_name", &helloworld::set_name)
.def("set_talk", &helloworld::set_talk)
.def("get_name", &helloworld::get_name)
.def("get_talk", &helloworld::get_talk);
}
封装类的时候,记得加上头文件 #include。构造函数方面:如果默认构造没有参数,用 init<>();如果有参数,比如 init,只需写明参数类型即可。成员变量可以直接暴露给 Python,但必须保证它们是公有的。通过访问控制可以限定读写权限:def_readonly() 表示只读,def_readwrite() 表示可读可写。至于 C++ 成员函数的参数,封装时不需要额外指定,直接写函数名就行——返回值如果不是特殊类型,也一样不需要刻意声明。
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。
















