简体   繁体   English

使用pybind11在c ++中调用python时如何通过引用传递参数

[英]How to pass arguments by reference when call python in c++ with pybind11

I'm using PyBind11 to run a Python interpreter, and I need to call a Python function in c++ with some pointer arguments.我正在使用PyBind11运行 Python 解释器,我需要使用一些指针参数在 c++ 中调用 Python 函数。

According to the docs of pybind11, it looks like that a argument being passed to Python side should be freed normally by the Python interpreter, instead of the c++ main program.根据 pybind11 的文档,看起来传递给 Python 端的参数应该由 Python 解释器正常释放,而不是由 c++ 主程序释放。 But this time the argument is a pointer to a static object, it should NOT be freed by anyone.但是这一次参数是一个指向静态对象的指针,它应该被任何人释放。 How to code such a binding/calling?如何编写这样的绑定/调用?

I know that pybind11::return_value_policy::reference can be used to prevent a returning result from being freed, but it is for a returning object, not for arguments.我知道pybind11::return_value_policy::reference可用于防止返回结果被释放,但它是用于返回对象,而不是用于参数。

Any hint will be appreciated!任何提示将不胜感激!

You can define a python wrapper inside an embedded module and access it from inside the python code.您可以在嵌入式模块中定义 python 包装器,并从 python 代码中访问它。 Then you can specify an appropriate return value policy when defining the getter.然后可以在定义 getter 时指定适当的返回值策略。

Then either call the getter directly from the python code, or, if you still want to use pass it as an argument, call the getter separately and store the result as a py::object which you can pass as an argument.然后直接从 python 代码调用 getter,或者,如果您仍想将其作为参数传递,请单独调用 getter 并将结果存储为py::object ,您可以将其作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM