更改 Python 函数内的基本(不可变)类型?
我正在使用 C++ SDK,其中有一个类似的函数(它有一个 python 包装器,但没有文档):
getPos ( int uvId, float & u, float & v ) const
How do Ispecify in Python so that the Passed Variables were Changed?
我尝试了这个例子,看看是否可以修改函数内部的浮点数,但它不起作用,所以打印了 12.0:
def change ( a ) :
a = 35.0
b = 12.0
change ( b )
print b
那么我如何调用这个函数,我可以在Python中更改2个外部浮点数?
相关:
I am using a C++ SDK where there is a function like (it has a python wrapper, but not docs):
getPos ( int uvId, float & u, float & v ) const
How do I specify in Python so that the passed variables are changed?
I tried this example to see if I could modify floats inside a function, but it didn't work, so printed 12.0:
def change ( a ) :
a = 35.0
b = 12.0
change ( b )
print b
So how do I call this function that I can change 2 external floats in Python?
Related:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在Python中:
In Python:
据我所知,Python 不支持按引用调用,因此您建议的确切代码不起作用(显然)。
为 C++ 函数生成 Python 包装器的工具(或人)必须做了一些特殊的事情来支持此函数(希望如此,否则您将无法使用它)。 你知道用什么工具来生成包装器吗?
通常这样的工具会生成某种容器数据类型:
As far I know, Python doesn't support call-by-reference, so the exact code you are suggesting doesn't work (obviously).
The tool (or person) that generated the Python wrapper for the C++ function must have done something special to support this function (hopefully, or you won't be able to use it). Do you know what tool was used to generate the wrapper?
Usually tools like this will generate some sort of container data type:
您将不得不求助于 ctypes。
具体请参阅 https://docs .python.org/library/ctypes.html#passing-pointers-or-passing-parameters-by-reference
You're going to have to resort to ctypes.
Specifically, see https://docs.python.org/library/ctypes.html#passing-pointers-or-passing-parameters-by-reference
对于简单的情况,让函数返回新值。
对于更复杂的情况,您可以传入一个对象或列表并进行更改:
编辑:
对于包装 C++ 引用,没有任何标准方法(基本 python 接口位于 C 级别 - 不是 C++) - 所以这取决于python 接口已实现 - 它可能是数组,或返回多个值。 我不确定 boost.python 如何处理它,但您可以从那里开始,或者可以在调试器下查看如何处理参数。
For simple cases have the function return the new value.
For more complicated cases you can pass in a object or a list and have that changed:
Edit:
For wrapping C++ references there isn't any standard way (basic python interfaces are at the C level - not C++) - so it depends how the python interface has been implemented - it might be arrays, or returning multiple values. I'm not sure how boost.python handles it but you might start there, or maybe look under a debugger to see how the parameter are handled.