我会很喜欢cppy的.但是,我使用的代码库大量使用了std.only_ptr、rValue指针和模板.我搞不懂如何将这些转换成我可以从Python调用的东西.

例如,我被困在如何从类创建std::map上.

我知道我可以通过做以下几件事得到std::map分:

test_map = Cpp.std.map[Cpp.std.string, Cpp.std.string]()
test_string = "value"
test_map["key"] = test_string
print(test_map["key"])

然而,当我这样做的时候:

test_map = Cpp.std.map[Cpp.std.string, Cpp.std.string]()
test_string = Cpp.std.string("value")
test_map["key"] = Cpp.std.move(test_string)
print(test_map["key"])

我得到

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[34], line 3
      1 test_map = Cpp.std.map[Cpp.std.string, Cpp.std.string]()
      2 test_string = Cpp.std.string("value")
----> 3 test_map["key"] = Cpp.std.move(test_string)
      4 print(test_map["key"])

TypeError: none of the 2 overloaded methods succeeded. Full details:
  std::string& std::map<std::string,std::string>::operator[](std::map<std::string,std::string>::key_type&& __k) =>
    logic_error: basic_string::_M_construct null not valid
  std::string& std::map<std::string,std::string>::operator[](const std::map<std::string,std::string>::key_type& __k) =>
    logic_error: basic_string::_M_construct null not valid

我不确定这为什么会失败.

我实际上想要构造的是从字符串到模板化类的映射,请参见:

import cppyy
import cppyy.gbl as Cpp

cppyy.cppdef(r"""\
template<typename T>
class MyClass {
public:
    MyClass(T t) : m_data(t) {}
    T m_data;
};
""")

但当我try 的时候:

test_map = Cpp.std.map[Cpp.std.string, Cpp.MyClass['double']]()
myClass  = Cpp.MyClass['double'](5.0)
test_map["key"] = Cpp.std.move(myClass)
print(test_map["key"])

我得到 a long error:

input_line_50:6:86: error: no member named 'operator[]' in 'std::map<std::__cxx11::basic_string<char>, MyClass<double>, std::less<std::__cxx11::basic_string<char> >, std::allocator<std::pair<const std::__cxx11::basic_string<char>, MyClass<double> > > >'
      new (ret) (MyClass<double>*) (&((std::map<std::string,MyClass<double> >*)obj)->operator[]((std::string&&)*(std::string*)args[0]));
                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
input_line_50:10:55: error: no member named 'operator[]' in 'std::map<std::__cxx11::basic_string<char>, MyClass<double>, std::less<std::__cxx11::basic_string<char> >, std::allocator<std::pair<const std::__cxx11::basic_string<char>, MyClass<double> > > >'
      ((std::map<std::string,MyClass<double> >*)obj)->operator[]((std::string&&)*(std::string*)args[0]);
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
input_line_51:6:86: error: no member named 'operator[]' in 'std::map<std::__cxx11::basic_string<char>, MyClass<double>, std::less<std::__cxx11::basic_string<char> >, std::allocator<std::pair<const std::__cxx11::basic_string<char>, MyClass<double> > > >'
      new (ret) (MyClass<double>*) (&((std::map<std::string,MyClass<double> >*)obj)->operator[]((const std::string&)*(const std::string*)args[0]));
                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
input_line_51:10:55: error: no member named 'operator[]' in 'std::map<std::__cxx11::basic_string<char>, MyClass<double>, std::less<std::__cxx11::basic_string<char> >, std::allocator<std::pair<const std::__cxx11::basic_string<char>, MyClass<double> > > >'
      ((std::map<std::string,MyClass<double> >*)obj)->operator[]((const std::string&)*(const std::string*)args[0]);
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[45], line 3
      1 test_map = Cpp.std.map[Cpp.std.string, Cpp.MyClass['double']]()
      2 myClass  = Cpp.MyClass['double'](5.0)
----> 3 test_map["key"] = Cpp.std.move(myClass)
      4 print(test_map["key"])

TypeError: none of the 2 overloaded methods succeeded. Full details:
  MyClass<double>& std::map<std::string,MyClass<double> >::operator[](std::map<std::string,MyClass<double> >::key_type&& __k) =>
    ReferenceError: none of the 2 overloaded methods succeeded. Full details:
  attempt to access a null-pointer
  attempt to access a null-pointer
  MyClass<double>& std::map<std::string,MyClass<double> >::operator[](const std::map<std::string,MyClass<double> >::key_type& __k) =>
    TypeError: none of the 2 overloaded methods succeeded. Full details:
  MyClass<double>& MyClass<double>::operator=(MyClass<double>&&) =>
    ValueError: could not convert argument 1 (object is not an rvalue)
  attempt to access a null-pointer

我做错了什么?

推荐答案

您可以使用.emplace插入Key/Value对,并且可以使用.atKey查找值.

示例:

#!/bin/python

import cppyy
import cppyy.gbl as Cpp

# the class with an added operator<< overload to support printing:
cppyy.cppdef(r"""\
template<typename T>
class MyClass {
public:
    MyClass(T t) : m_data(t) {}
    T m_data;
    friend std::ostream& operator<<(std::ostream& os, const MyClass& mc) {
        return os << mc.m_data;
    }
};
""")

from cppyy.gbl import MyClass

test_map = Cpp.std.map[Cpp.std.string, MyClass['double']]()

myObj = MyClass['double'](5.0)

# add a key/value pair
test_map.emplace("key", Cpp.std.move(myObj))

# print the value mapped to the key:
print(test_map.at("key"))

# loop and print keys and values
for key, value in test_map:
    print(key, value)

输出:

5
key 5

Python相关问答推荐

如何使用Tkinter创建两个高度相同的框架(顶部和底部)?

阅读Polars Python中管道的函数定义

由于瓶颈,Python代码执行太慢-寻求性能优化

添加包含中具有任何值的其他列的计数的列

当密钥是复合且唯一时,Pandas合并抱怨标签不唯一

如何使用scipy从频谱图中回归多个高斯峰?

理解Python的二分库:澄清bisect_left的使用

Odoo 14 hr. emergency.public内的二进制字段

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

ThreadPoolExecutor和单个线程的超时

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

在Python中调用变量(特别是Tkinter)

如何将数据帧中的timedelta转换为datetime

使用字典或列表的值组合

如何在Gekko中使用分层条件约束

从嵌套极轴列的列表中删除元素

极点替换值大于组内另一个极点数据帧的最大值

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

Pandas:将值从一列移动到适当的列

将数字数组添加到Pandas DataFrame的单元格依赖于初始化