Reputation: 343
I'm trying to get the values from a pointer to a float array, but it returns as c_void_p in python
The C code
double v;
const void *data;
pa_stream_peek(s, &data, &length);
v = ((const float*) data)[length / sizeof(float) -1];
Python so far
import ctypes
null_ptr = ctypes.c_void_p()
pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length))
The issue being the null_ptr has an int value (memory address?) but there is no way to read the array?!
Upvotes: 4
Views: 13749
Reputation: 4867
When you pass pointer arguments without using ctypes.pointer or ctypes.byref, their contents simply get set to the integer value of the memory address (i.e., the pointer bits). These arguments should be passed with byref
(or pointer
, but byref
has less overhead):
data = ctypes.pointer(ctypes.c_float())
nbytes = ctypes.c_sizeof()
pa_stream_peek(s, byref(data), byref(nbytes))
nfloats = nbytes.value / ctypes.sizeof(c_float)
v = data[nfloats - 1]
Upvotes: 0
Reputation: 69182
To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested):
vdata = ctypes.c_void_p()
length = ctypes.c_ulong(0)
pa_stream_peek(stream, ctypes.byref(vdata), ctypes.byref(length))
fdata = ctypes.cast(vdata, POINTER(float))
Upvotes: 1
Reputation: 339
You'll also probably want to be passing the null_ptr using byref, e.g.
pa_stream_peek(stream, ctypes.byref(null_ptr), ctypes.c_ulong(length))
Upvotes: 0
Reputation: 46773
My ctypes is rusty, but I believe you want POINTER(c_float) instead of c_void_p.
So try this:
null_ptr = POINTER(c_float)()
pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length))
null_ptr[0]
null_ptr[5] # etc
Upvotes: 3