当在C+&#x2B中调用Python时,如何通过参考通过参数通过参数。与pybind11

发布于 2025-02-04 08:36:44 字数 313 浏览 2 评论 0原文

我正在使用 pybind11 运行Python解释器,并且我需要使用一些指针参数在C ++中调用Python函数。

根据PYBIND11的文档,看来Python解释器正常释放了传递给Python方面的论点,而不是C ++主程序。 但是这次论点是指向静态对象的指针,它应该 被任何人释放。如何编码这样的绑定/调用?

我知道pybind11 :: return_value_policy ::参考可用于防止返回结果被释放,但这是用于返回对象,而不是参数。

任何提示都将不胜感激!

I'm using PyBind11 to run a Python interpreter, and I need to call a Python function in c++ with some pointer arguments.

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.
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.

Any hint will be appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿忘初心 2025-02-11 08:36:44

您可以在并从Python代码内部访问它。然后,您可以在定义getter时指定适当的返回值策略,例如:


extern MyObject global_object;

PYBIND11_EMBEDDED_MODULE(statics, m) {
  m.def(
    "global_object",
    []() -> MyObject& {
      return global_object;
    },
    pybind11::return_value_policy::reference
  );
}

然后直接从python代码中调用statics.global_object()来自C ++的参数,在解释器中调用statics.global_object(),然后将结果存储在C ++中,作为py :: object,您可以将其作为参数传递。

You can define a python wrapper inside an embedded module and access it from inside the python code. Then you can specify an appropriate return value policy when defining the getter, like this:


extern MyObject global_object;

PYBIND11_EMBEDDED_MODULE(statics, m) {
  m.def(
    "global_object",
    []() -> MyObject& {
      return global_object;
    },
    pybind11::return_value_policy::reference
  );
}

Then either call the statics.global_object() directly from the python code, or, if you still want to use pass it as an argument from C++, call the statics.global_object() in the interpreter and store the result in C++ as a py::object which you can then pass as an argument.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文