2

I am using a C Library and interfacing it with python, without going into too much detail, my library has a C function which we will call 'foo' that returns void const* (it either returns float const* or double const* depending on application). In python I declared this as:

from ctypes import *
mylib = cdll.LoadLibrary('mylib.so')

foo = mylib.foo
foo.restype = c_void_p

From now we will assume that we are using float not double and given the expected dimensions of the pointer as 'D' e.g. 12

D = 12

I am trying to do a deep copy of the return value into a python numpy array so that I don't need to worry about the memory allocated by the C Library being freed, I have tried implementing it as follows:

import numpy as np
x = np.frombuffer(foo(), np.float32, D * np.dtype(np.float32).itemsize).copy()

AttributeError: 'int' object has no attribute '__buffer__'

But it doesn't seem to work, I thought that the return type of 'foo' would be a ctypes c_void_p type python object but actually it is just an int. I am guessing the value of the int corresponds to the address in memory of the first float in the array but maybe I am wrong. There must be an easy way of doing this, has anybody got any suggestions?

If you would like more details (on the library, etc.) let me know I tried to keep the question simple.

Thanks.

1
  • 1
    x = np.frombuffer((c_float * D).from_address(foo()), np.float32).copy() Commented Feb 3, 2016 at 18:13

1 Answer 1

3

Thanks to eryksun in comments:

x = np.frombuffer((c_float * D).from_address(foo()), np.float32).copy()
Sign up to request clarification or add additional context in comments.

Comments

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.