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++ 成员函数的参数,封装时不需要额外指定,直接写函数名就行——返回值如果不是特殊类型,也一样不需要刻意声明。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















