Boost-python封装Cpp代码供Python调用
作者:吹吹风会发光
时间:2026-06-28
浏览:0
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++ 成员函数的参数,封装时不需要额外指定,直接写函数名就行——返回值如果不是特殊类型,也一样不需要刻意声明。
作者最新文章
iphone蓝牙连接ipad有什么用及连接方法教程
2026-09-21 17:28
PDF怎么取消密码保护?4种解锁方法整理
2026-09-08 18:23
三星 Galaxy Z Fold8 内屏边角支撑偏软?实测与官方回应
2026-09-08 16:39
手机Excel表格制作教程:小屏幕高效录入与格式调整指南
2026-09-04 09:27
PDF文档按页转换成图片怎么做?在线转换步骤整理
2026-09-03 11:06
上一篇:
Python: Tools
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































