3. 基础类型绑定:int、float、string、vector 等 C++ 类型如何在 Python 中自动转换
好,咱们今天聊点实在的。
Boost.Python 最让我觉得爽的地方,就是它处理基础类型的方式——几乎不用你操心。你写个 C++ 函数,返回 int,Python 那边拿到的就是 int;你传个 std::string 进去,Python 那边直接当 str 用。说白了,Boost.Python 在背后帮你做了一层「自动翻译」。
但别高兴太早。我当年第一次用的时候,就踩了个坑——std::vector 并不会自动变成 Python 的 list。嗯,这里要注意,基础类型和容器类型,处理方式完全不同。
3.1 自动转换的「白名单」
Boost.Python 默认支持以下 C++ 类型与 Python 类型的双向转换:
| C++ 类型 | Python 类型 | 转换方向 |
|---|---|---|
bool |
bool |
双向 |
int / long |
int |
双向 |
float / double |
float |
双向 |
std::string |
str |
双向 |
char const* |
str |
C++ → Python |
std::wstring |
unicode |
双向 |
你看,这些都是最常用的类型。你写个 C++ 函数:
int add(int a, int b) {
return a + b;
}
然后暴露给 Python:
BOOST_PYTHON_MODULE(example) {
def("add", add);
}
Python 那边直接就能用:
import example
print(example.add(3, 5)) # 输出 8
完全不需要写任何转换代码。我个人习惯把这种类型叫做「零摩擦类型」——写起来最省心。
3.2 字符串的「坑」与「解」
std::string 和 Python str 的转换,大部分时候是透明的。但有一个细节我提醒你注意:空字符串和空指针。
我曾经在项目中遇到过一个 bug:C++ 函数返回 char const*,如果指针是 nullptr,Boost.Python 会直接抛异常。为什么?因为它没法把 nullptr 转换成 Python 的 None——默认情况下它不会这么做。
char const* 作为返回值,请确保它永远不会是 nullptr。要么改用 std::string,要么手动处理空指针情况。
解决方案其实很简单:
std::string safe_get_name() {
const char* name = get_name_internal();
return name ? std::string(name) : "";
}
或者,你也可以用 boost::optional<std::string>,但那是后面章节的内容了。
3.3 vector 不会自动转换!
好,重点来了。
很多新手会以为 std::vector<int> 会自动变成 Python 的 list。我告诉你,不会。Boost.Python 默认只处理标量类型,不处理容器。
你如果直接写:
std::vector<int> get_scores() {
return {90, 85, 88};
}
BOOST_PYTHON_MODULE(example) {
def("get_scores", get_scores);
}
Python 那边调用 example.get_scores() 会得到一个 Boost.Python.vector<int> 对象——不是 list,不能直接 for 遍历,也不能切片。说白了,它是个「四不像」。
std::vector 像 Python list 一样用,必须手动注册转换器,或者用 boost::python::list 做桥接。
3.4 两种解决方案
我个人推荐两种做法,看场景选。
方案一:用 boost::python::list 做中间层
你可以在 C++ 里手动把 vector 转成 boost::python::list:
#include <boost/python/list.hpp>
boost::python::list get_scores_py() {
std::vector<int> scores = {90, 85, 88};
boost::python::list result;
for (int s : scores) {
result.append(s);
}
return result;
}
这样 Python 拿到的就是真正的 list。缺点嘛——你得手动写循环,代码有点啰嗦。
方案二:注册 vector<int> 的自动转换器
Boost.Python 提供了 vector_indexing_suite,可以一键注册:
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
struct World {
std::vector<int> scores;
};
BOOST_PYTHON_MODULE(example) {
class_<World>("World")
.def_readwrite("scores", &World::scores)
;
// 注册 vector<int> 的自动转换
class_<std::vector<int>>("IntVector")
.def(vector_indexing_suite<std::vector<int>>());
}
这样,World.scores 在 Python 里就能像 list 一样用——支持 len()、[] 索引、for 遍历,甚至 append()。
vector,方案一更简单。如果项目里大量用到 vector<int> 或 vector<string>,方案二一劳永逸。
3.5 知识体系总览
下面这张图,帮你把本章的核心逻辑串起来:
3.6 实战:一个完整的例子
把上面这些串起来,写一个完整的模块:
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <vector>
#include <string>
std::string greet(std::string name) {
return "Hello, " + name + "!";
}
double average(std::vector<double> values) {
double sum = 0;
for (double v : values) sum += v;
return sum / values.size();
}
BOOST_PYTHON_MODULE(mymodule) {
using namespace boost::python;
def("greet", greet);
def("average", average);
// 注册 vector<double> 自动转换
class_<std::vector<double>>("DoubleVector")
.def(vector_indexing_suite<std::vector<double>>());
}
Python 端:
import mymodule
print(mymodule.greet("Python")) # Hello, Python!
print(mymodule.average([1.0, 2.0, 3.0])) # 2.0
你看,greet 的字符串转换完全自动,average 的 vector 因为注册了 vector_indexing_suite,也能直接传 Python list。嗯,这就是我想要的「丝滑感」。
3.7 小结
- int、float、string、bool 这些标量类型,Boost.Python 自动双向转换,零代码。
- std::vector 不会自动转换,必须手动注册或桥接。
- 注册用
vector_indexing_suite,桥接用boost::python::list。 - 字符串注意空指针问题,建议统一用
std::string。
我个人觉得,基础类型的绑定是 Boost.Python 最「甜」的部分——你几乎感觉不到它的存在。但一旦涉及到容器,就得稍微动点脑子了。不过别担心,后面我们会讲到更复杂的类型,比如自定义类和 STL 容器的高级用法。