在 Boost::Python 中通过引用传递
考虑一下这样的事情:
struct Parameter
{
int a;
Parameter(){a = 0;}
void setA(int newA){a = newA;}
};
struct MyClass
{
void changeParameter(Parameter &p){ p.setA(-1);}
};
好吧,让我们快进,想象一下我已经包装了这些类,将所有内容暴露给 python,并想象我在 C++ 代码中实例化了 Parameter 对象,我将其传递给 python 脚本,并且 python 脚本使用一个 MyClass 对象,用于修改我在 C++ 代码开头创建的 Parameter 实例。
代码执行后,C++中的参数实例没有改变!这意味着它是通过值(或类似的东西:S)传递的,而不是通过引用传递的。但我以为我声明它是通过引用传递的...
我似乎找不到关于通过引用传递的 Boost::Python 文档(尽管似乎有足够的关于通过引用返回的文档...)。有人可以给一些提示或指示吗?
Consider something like:
struct Parameter
{
int a;
Parameter(){a = 0;}
void setA(int newA){a = newA;}
};
struct MyClass
{
void changeParameter(Parameter &p){ p.setA(-1);}
};
Well, let's fast forward, and imagine I already wrapped those classes, exposing everything to python, and imagine also I instantiate an object of Parameter in the C++ code, which I pass to the python script, and that python script uses a MyClass object to modify the instance of Parameter I created at the beginning in the C++ code.
After that code executes, in C++ Parameter instance is unchanged!!! This means it was passed by value (or something alike :S), not by reference. But I thought I declared it to be passed by reference...
I can't seem to find Boost::Python documentation about passing by reference (although there seems to be enough doc about returning by reference...). Can anyone give some hint or pointer please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Python 没有引用,因此当您传递对 python
boost::python
的引用时,会调用对象的copy-ctor
。在这种情况下,您有两种选择:用指针(或智能指针)替换引用,或者将您自己的“智能引用”对象/包装器传递到 python 中。
Python doesn't have references, so when you pass reference to python
boost::python
callscopy-ctor
of your object.In this case you have two choices: Replace references with pointers (or smart-pointers) or pass into python your own 'smart-reference' object/wrapper.