2

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!

Leon
  • 1,489
  • 1
  • 12
  • 31

1 Answers1

0

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.

unddoch
  • 5,790
  • 1
  • 24
  • 37