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

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers that worked passing in the POINTER(c_float)() worked perfectly.. I also add to update the type wrapper like from pa_stream_peek.argtypes = [POINTER(pa_stream), POINTER(POINTER(None)), POINTER(c_size_t)] to pa_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]
1

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))

Comments

0

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))

Comments

0

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]

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.