1

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.

Community
  • 1
  • 1
shaoyl85
  • 1,854
  • 18
  • 30

1 Answers1

0
import ctypes, numpy
bptr = int(b.cast())
barray = ctypes.c_byte*200
barray = barray.from_address(bptr)
z = numpy.ctypeslib.as_array(barray)
Hwa
  • 1
  • 1
  • 7
    Please don't post answers that contain only code. Go ahead and explain your solution how you solved OP's issue. – L. Guthardt May 17 '18 at 07:28