Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a byte array to a C++ function that accepts a void pointer

Tags:

python

boost

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
like image 746
n. 1.8e9-where's-my-share m. Avatar asked Oct 18 '22 06:10

n. 1.8e9-where's-my-share m.


1 Answers

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.

like image 109
sehe Avatar answered Oct 20 '22 22:10

sehe