引用从 Python 传递到 Boost::p ython 并返回 Python
reference passing from python to boost::python and back to python
我是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 实践。
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Pybind11:将元组列表从Python传递到C++
- 如何在c++中使用引用实现类似python的行为
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 递归列出所有目录中的C++与Python与Ruby的性能
- IPC使用多个管道和分支进程来运行Python程序
- 从python中调用C++函数并获取返回值
- Python 3.7 和 excess_args 的 SWIG 问题
- 在 boost::p ython 中的 python 对象中运行 python 代码
- Boost::P ython,将元组转换为Python有效,矢量<tuple>不
- 如何使用 boost::p ython 创建和使用 Python 对象的实例
- 使用 boost::p ython,如何将结构体向量作为字典列表返回给 Python
- 可以提升::p ython将对象的所有权传递给python回调函数
- 使用 boost::p ython 从C++创建 python collections.namedtuple
- 如何使用 boost::p ython 从 Python 类型中提取包装的C++类型
- 如何使用Boost::P ython打印到Python终端
- 引用从 Python 传递到 Boost::p ython 并返回 Python
- 如何使用<double>boost::p ython通过引用将non-const std::vector传递给Python?
- 使用 boost::p ython 将虚拟成员函数从 C++ 公开到 Python
- 无法使用 boost::p ython 更改传递给 python 函数的对象