tags:

views:

1129

answers:

4

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?!

+1  A: 

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
Unknown
Cheers that worked passing in the POINTER(c_float)() worked perfectly.. I also add to update the type wrapper likefrom pa_stream_peek.argtypes = [POINTER(pa_stream), POINTER(POINTER(None)), POINTER(c_size_t)]topa_stream_peek.argtypes = [POINTER(pa_stream), POINTER(POINTER(c_float)), POINTER(c_size_t)]giving data = POINTER(c_float)() pa_stream_peek(stream, data, ctypes.c_ulong(length)) v = data[0]
KillerKiwi
A: 

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))
igkuk7
+1  A: 

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))
tom10
A: 

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]
Nathan Kitchen