mbs9
mbs9

Reputation: 95

Pybind11 automatic type conversions memory management

I am using Pybind11 to make a Python C++ extension module, and have the following code:

#include <pybind11/pybind11.h>
#include <string.h>
namespace py = pybind11;

int getLength(char* arg) {
   return strlen(arg);
}

PYBIND11_MODULE(example, m) {
    m.def("getLength", &getLength, "Get length using strlen", py::arg("arg"));
}

From the type conversion documentations, when I call getLength from Python, Pybind11 converts Python's str type to C++ char*. I assume that the memory for the new char* argument is allocated on the heap. My question is: does Pybind11 deallocate this on return, or I need to add delete[] arg; at the end of my function?

I know that if I were to change my function, to accept py:str (Python's string type), then manually converted it to C++ char* I would be responsible for (de)allocation. Does this hold for built in conversions too?

Does Pybind11 handle memory management of the results of automatic conversions, or do I need to do that?

Though I couldn't find the answer in the docs, I link it anyway: https://pybind11.readthedocs.io/en/stable/advanced/cast/overview.html#list-of-all-builtin-conversions

Upvotes: 1

Views: 478

Answers (1)

ChrisD
ChrisD

Reputation: 967

In this case it will end up using the c-style string type caster, which in turn will instantiate a std::string here, and the memory will be cleaned up when this std::string's destructor is called. (unless it's an optimized small string which was allocated on the stack).

Although I am a little out of my depth here, it has to be a copy since python strings are (technically) immutable. But pybind11 also allows conversions to a std::string_view which does not make a copy.

Upvotes: 1

Related Questions