1

I would like to create a numpy.darray exactly at the location where a ctypes.c_void_p pointer is pointing to.

buffer_ = ctypes.c_void_p()
# magically let the API point it to a special memory location
numpy_buffer_ = numpy.ndarray(shape, dtype=dtype, buffer=buffer_)

However, I am getting the error:

TypeError: buffer is too small for requested array

I got the general idea to solve this problem like this from another thread, where it is used slightly differently:

numpy.ndarray(shape, dtype=dtype, buffer=c_void_p.from_address(address))

However, as I already have a c_void_p pointing to the correct address, I hoped I could use it.

Any ideas, why my buffer appears too small? (It also does not work, if I put a tiny shape to my ndarray)

Best,

gbrown

G.Brown
  • 214
  • 2
  • 12
  • 1
    Is your buffer initialized with a size different from 0? I don't know if you really have the choice but this is something that could cause your problem – Maël Pedretti Sep 25 '18 at 09:10
  • My buffer is a ctypes.c_void_p(), so I do not think it has a size. However, in the example from the other thread, he is using a c_void_p as well, so I would expect that it must work somehow. – G.Brown Sep 25 '18 at 09:11
  • > it must work somehow. Yeah sure, but why don't you try to follow a working example first before trying to do anything else? I understand that you try by your side but maybe that the difference of your c_void_p initialization makes the difference with the one from the example. Have you read the documentation? Are you sure those two ways produce the exact same result? I don't want to stop you in your learning initiative but developpers write documentation and exemples for a reason.. – Maël Pedretti Sep 25 '18 at 09:24
  • 2
    `numpy.ctypeslib.as_array(obj, shape=None)` https://stackoverflow.com/questions/23930671/how-to-create-n-dim-numpy-array-from-a-pointer – Joe Sep 25 '18 at 09:31
  • Possible duplicate of [How to create n-dim numpy array from a pointer?](https://stackoverflow.com/questions/23930671/how-to-create-n-dim-numpy-array-from-a-pointer) – Joe Sep 25 '18 at 09:35
  • @Mael Pedretti: From what I got, c_void_p.value is it's address, but that leads to exactly the same error. So, either the example does not work (though accepted) or I am doing something wrong (which I assume). Did read the doc and my attempt should work from what I understand. – G.Brown Sep 25 '18 at 09:39
  • 1
    @Joe: That seems to solve the problem. Sorry, I must have missed this during my search! Thanks to the both of you! – G.Brown Sep 25 '18 at 09:42
  • check @Joe comment – Maël Pedretti Sep 25 '18 at 09:42
  • Please don't post sporadic pieces of code, but check [\[SO\]: How to create a Minimal, Complete, and Verifiable example (mcve)](https://stackoverflow.com/help/mcve). – CristiFati Sep 25 '18 at 09:46

0 Answers0