cppyy - 如何调用接受集合的 C++ 函数?

cppyy - how to call a c++ function that accepts a set?

假设我有以下 C++ 函数:

int summap(const map<int,int>& m) {
    ...
}

我尝试使用 cppyy 从 Python 调用它,方法是发送一条字典:

import cppyy
cppyy.include("functions.hpp")
print(cppyy.gbl.summap({55:1,66:2,77:3}))

我收到一个错误:

TypeError: int ::summap(const map<int,int>& v) =>
    TypeError: could not convert argument 1

如何调用这个函数?

Python的dict和C++的std::map没有关系(两者内部结构完全不同),所以需要转换,cppyy目前没有自动的,所以做这样的事情:

cppm = cppyy.gbl.std.map[int, int]()
for key, value in {55:1,66:2,77:3}.items():
    cppm[key] = value

然后将 cppm 传递给 summap。

自动支持 python list/tuple -> std::vector 是可用的,但是,它也不比复制更聪明(同样,b/c 内部结构是完全不同),因此任何自动 std::map <-> python dict 转换在内部仍然必须像上面那样进行复制。