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.

1 Answer 1

0
import ctypes, numpy
bptr = int(b.cast())
barray = ctypes.c_byte*200
barray = barray.from_address(bptr)
z = numpy.ctypeslib.as_array(barray)
Sign up to request clarification or add additional context in comments.

1 Comment

Please don't post answers that contain only code. Go ahead and explain your solution how you solved OP's issue.

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.