I would like to create a Python buffer object (either writable or not) from a C++ pointer, such that it can be passed to the numpy.frombuffer
function. Can someone let me know how to do it?
Here is my example SWIG-wrapped C++ function which returns a pointer:
uint8_t* some_function() {return new uint8_t[200];}
After SWIG wrap it, I followed this post to create a buffer object in python:
x = some_function()
b = buffer_frompointer(x)
z = numpy.frombuffer(b, dtype=numpy.uint8)
The last statement returns an error saying the __buffer__
attribute is not found. I guess this is because the variable b
here is not really a buffer object in the python sense. So what shall I do?
ps. I don't want an additional copy of the memory when creating the numpy array.
ps. Let's not worry about the memory leak problem for now.
UPDATE:
I'm still interested in a solution to this question, but in case no one answers it, I'll go with a workaround in another question I asked, although that solution is not preferred because of the use of deprecated interfaces.