提振.Python return_internal_reference策略
boost.python return_internal_reference policy
对于以下两个类:
class A {
};
class B {
public:
B()
: a_(std::make_shared<A>())
{}
std::shared_ptr<A> a_;
};
有以下简单的boost.python
包装
A& get_a(const B& b) {
return *b.a_; // intentionally, no check here; doesn't matter for the example
}
boost::python::class_<A, std::shared_ptr<A>>("A");
boost::python::class_<B>("B")
.def("get_a", &get_a, boost::python::return_internal_reference<>());
在Python中有简单的成员检索:
import ext
b = ext.B()
a1 = b.get_a()
a2 = b.get_a()
我期望的是
id(a1) == id(a2)
对于上面的情况不成立,这意味着创建了两个不同的PyObject
作为A
包装器。为什么?return_internal_reference
策略不阻止创建多个临时对象吗?
如果我从get_a
返回std::shared_ptr<A>
,程序编译失败。
这个问题和这个问题有相似之处。然而,在后一种情况下,有可能不被跟踪的临时对象。另一方面,在这里,成员变量的包装器存储在python变量中。
return_internal_reference
策略允许在没有Boost的情况下返回内部保存对象的指针或引用。Python复制引用。这并不意味着后续调用将返回相同的Python对象。
下面是一个示例,说明在使用return_internal_reference
时不会复制c++对象,并且多个离散的Python对象可以嵌入对同一个c++对象的引用:
#include <boost/python.hpp>
#include <cstdint> // std::uintptr_t
struct spam
{
uintptr_t id() { return reinterpret_cast<uintptr_t>(this); }
};
struct egg {};
spam& get_spam(const egg&)
{
static spam instance;
return instance;
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<spam>("Spam")
.def("id", &spam::id)
;
python::class_<egg>("Egg")
.def("get_spam", get_spam, python::return_internal_reference<>())
;
}
互动用法:import example
egg = example.Egg()
spam1 = egg.get_spam()
spam2 = egg.get_spam()
assert(spam1.id() == spam2.id()) # reference same C++ object
assert(id(spam1) != id(spam2)) # non-identical Python objects
相关文章:
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- C++17中的并行执行策略
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 运行时执行策略不同
- Tensorflow c++ api undefined reference to 'tflite::D efaultErrorReporter()'
- 编译器上的策略数据结构不起作用
- 不断"Attempting to reference a deleted function"
- 我应该在简单的策略游戏中为各个派系使用类吗 - C++
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- std::iterator::reference 必须是引用吗?
- C++/SDL "initial value of reference to a non-const must be an lvalue"
- 没有执行策略的 std::transform_reduce 是可移植的吗?
- C++ 运算符修改/元编程策略,用于不那么冗长的语法
- 为什么在使用 SDL2 时仍然收到'undefined reference'链接器错误?
- 使用 Qt5 SQL 进行异步数据库访问的策略
- OpenCV undefined reference to 'cv::imread(cv::String const&, int)'