[C++-sig] Passing memory allocated in C++ to Python

Stefan Seefeld stefan at seefeld.name
Tue Jan 12 14:06:03 EST 2016


On 12.01.2016 13:54, Tony Cappellini wrote:
>
> > In your something class, the data type returned from allocate_memory()
> > needs to be something that Python understands. Since that allocation
> > function (member) will be allocating 100s of MB of memory, how will
> > this memory map to a Python data type?
>
> >>Does it have to be a Python (native) data type ? Could you explain your
> >>use-case a little more ?
>
> It needs to be a data type that can be allocated in C++ but accessible
> in Python

"accessible" is too vague. The question is what interface you need,
whether an object-oriented one with methods to access and modify the
internal state, or one giving you unstructured access to the raw data.

>
> >>Could you explain your use-case a little more ?
> I have C++ code which is interfacing to a driver, from Python.
> The user invokes a python function which calls my C++ code (via
> Boost). The C++ code makes a C++ structure, allocates memory for the
> ioctl call,
> puts a pointer to the allocated memory into the C++ structure (as well
> as filling in other structure members), calls the ioctl and returns
> the success/failure
> results to Python. The user needs a way to get access to the allocated
> memory, which was filled in by the ioctl call.

Can you share your code, or at least a stripped-down version ? I think
at this point it would make more sense to go over some specifics.
Your description above doesn't sound very object-oriented. You are
calling a function that returns the success of the operation. What you
actually want is return an object that holds the state (including the
memory you are talking about), which you can then manipulate in
subsequent calls.

Even some pseudo-code would do, to discuss the general idea.

> I should have mentioned that I am using Python 2.7 (as part of a group
> project- others are using Python 2.7 as well).
>
> Python 3.x is out of the question at the moment, but the memory view
> looks like an interesting idea.

Fine, I just mentioned it to illustrate the idea. There are other APIs
to achieve the same.

Regards,
    Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list