python Python双指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/828139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:56:16  来源:igfitidea点击:

Python double pointer

pythonctypes

提问by KillerKiwi

I'm trying to get the values from a pointer to a float array, but it returns as c_void_p in python

我正在尝试从指向浮点数组的指针获取值,但它在 python 中返回为 c_void_p

The C code

C 代码

double v;
const void *data;  
pa_stream_peek(s, &data, &length);  
v = ((const float*) data)[length / sizeof(float) -1];

Python so far

到目前为止的 Python

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

问题是 null_ptr 有一个 int 值(内存地址?)但没有办法读取数组?!

采纳答案by Unknown

My ctypes is rusty, but I believe you want POINTER(c_float) instead of c_void_p.

我的 ctypes 生锈了,但我相信你想要 POINTER(c_float) 而不是 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

回答by tom10

To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested):

要以模仿您的 C 代码的方式使用 ctypes,我会建议(而且我没有实践,这是未经测试的):

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

回答by Nathan Kitchen

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 byrefhas less overhead):

当您在不使用 ctypes.pointer 或 ctypes.byref 的情况下传递指针参数时,它们的内容只会被设置为内存地址的整数值(即指针位)。这些参数应该用byref(or pointer,但byref开销较小)传递:

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]

回答by igkuk7

You'll also probably want to be passing the null_ptr using byref, e.g.

您可能还想使用 byref 传递 null_ptr,例如

pa_stream_peek(stream, ctypes.byref(null_ptr), ctypes.c_ulong(length))