【问题标题】:cppyy - how to call a c++ function that accepts a set?cppyy - 如何调用接受集合的 c++ 函数?
【发布时间】:2019-05-26 15:10:38
【问题描述】:

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

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

我尝试使用 cppyy 从 Python 调用它,方法是发送一个 dict:

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-3.x cppyy


    【解决方案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 列表/元组的自动支持 -> std::vector 是可用的,但在那里,它也不比复制更聪明(同样,b/c 内部结构完全不同),所以任何自动 std::map python dict 转换在内部仍然需要像上面那样做一个副本。

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 1970-01-01
      • 2023-03-16
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      相关资源
      最近更新 更多