引用从 Python 传递到 Boost::p ython 并返回 Python

reference passing from python to boost::python and back to python

本文关键字:Python ython 返回 引用 Boost      更新时间:2023-10-16

我是python和boost::p ython的新手,请原谅我的无知。

我的代码有一个python - C++交互,这是通过boost::p ython完成的。我正在将python字典引用传递给C++:

C++代码 :

boost::python::class_<ABC> ("ABC")
    .def("set_input",&ABC::set_input)
    ;
struct ABC {
boost::python::dict* signal_dictionary ;
 void insert_into_dict(int key,CellData cell_data) {
    if (!signal_dictionary->has_key(key) { 
       signal_dictionary->operator[](key)  = cell_data;
   }
 }
void set_input(boost::python::dict &signal_dict_t ) {
     signal_dictionary = &signal_dict_t;
}

我的想法是将python字典的地址传递给C++。在C++中填充数据。并在 enitre 填充完成后在 python 中访问它.函数insert_into_dict间歇性调用,并在字典中填充数据。但是我收到以下错误:AttributeError: 'Boost.Python.function' 对象没有属性 '_contains_'

这来自:signal_dictionary->has_key(键)。似乎 boost::p ython 将signal_dictionary读作 boost::p ython::function,即使它是一个 boost::p ython::d ict 。有没有办法对它进行类型转换来提升::p ython::d ict .

提前致谢!!

首先,没有必要为我是新手而道歉,我们都在这里学习!

对于您的特定问题,类型之间似乎存在混淆。当你使用 boost::p ython 时,你通过一个C++接口来处理 Python 对象,有时这两种截然不同的语言范式之间的交互会导致棘手的情况。

在您的情况下,我相信问题出在以下行上:signal_dictionary->has_key(键)。boost::p ython::d ict 类没有名为 has_key() 的方法。相反,您应该使用 contains() 方法。以下是更正方法:

if (!signal_dictionary->contains(key)) { 
    (*signal_dictionary)[key]  = cell_data;
}

这应该可以解决您遇到的属性错误。看起来包含错误是尝试访问 boost::p ython::d ict 中不存在的has_key的结果,然后 boost::p ython 尝试调用 Python 方法包含但找不到它(因为它没有作为包含实现)。

另外需要注意的是,由于您是 Python 的新手,因此 has_key() 方法自 3.0 版起已在 Python 中弃用。使用 in 关键字或 contains() 方法来检查字典中是否有键更 pythonic。

这也是 boost::p ython::d ict 没有 has_key() 方法的另一个原因——它遵循现代 Python 实践。