7

I'm using boost::python to export some C++ functions that expect a void*. They interpret it as raw memory (an array of bytes) internally. Think read and write for some very special purpose device.

How do I pass a Python bytearray to such a function?

I have tried using ctypes.c_void_p.from_buffer(mybytearray) but this doesn't match the signature of the function.

Here's the minimal example:

#include <boost/python.hpp>

void fun_voidp(void*) {}

BOOST_PYTHON_MODULE(tryit) {
    using namespace boost::python;
    def("fun_voidp", fun_voidp);
}

And at the python side:

import tryit
import ctypes
b = bytearray(100)
tryit.fun_voidp(b) # fail
tryit.fun_voidp(ctypes.c_void_p.from_buffer(b)) # fail
tryit.fun_voidp(ctypes.c_void_p.from_buffer(b).value) # fail

1 Answer 1

2

I'd very much fix the function prototype to take char* and go with the last python line.

There's no reason to use void* in C++. I understand if the API does, but it shouldn't be hard to wrap it with your own function.

Sign up to request clarification or add additional context in comments.

3 Comments

It's a legacy API in use by other projects, changing it is impossible and wrapping it defeats the idea of exporting it as is. I could wrap it in a function that accepts a python object...
"defeats the idea" - what is the actual worth of that idea? (honest question)
There are many such functions and writing a wrapper for each one would be a lot of work. Perhaps I will go this route anyway, to make the interface more idiomatic Python (i.e. return a new byte array instead of having one as an argument and filling it). Still I'd like to know if there's an option to use a byte array as void* with boost (one can easily do that with ctypes for example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.