python-ctypes,检索发送到共享c库的void指针的值

python-ctypes,检索发送到共享c库的void指针的值,python,ctypes,Python,Ctypes,我正在用ctypes从dll调用cpp函数 函数定义是 int foo(strc *mystrc, int *varsize); 结构: typedef struct { int type; int count; void *value; } strc; 因此,我在python中尝试的是定义: class strc(ctypes.Structure): _fields_ = [('type', ctypes.c_int), ('

我正在用ctypes从dll调用cpp函数

函数定义是

int foo(strc *mystrc, int *varsize);
结构:

typedef struct
{
    int type;
    int count;
    void *value;
} strc;
因此,我在python中尝试的是定义:

class strc(ctypes.Structure):
    _fields_ = [('type', ctypes.c_int),
                ('count', ctypes.c_int),
                ('value', ctypes.c_void_p)]
并将函数调用为

varsize = ctypes.c_int()
mystrc = strc()
foo(ctypes.byref(mystrc), ctypes.byref(varsize))
我完全可以调用该函数并检索除“value”之外的所有值。它应该是一个由“type”表示的变量数组,大小为“varsize”,并且是一个由“count”变量组成的数组

如何检索由void指针指示的内容?

模板void iterate\u strc\u值(const void*值,int size)
template<class T> void iterate_strc_value(const void* value, int size)
{
    const T* element = reinterpret_cast<const T*>(value);
    for(int offset = 0; offset != size; ++offset)
        *(element + offset) // at this point you have the element at the offset+1th position
}

switch(strc_var.type)
{
    case 0: iterate_strc_value<char>(strc_var.value, element_count); break;
    case 1: iterate_strc_value<int>(strc_var.value, element_count); break;
    case 2: iterate_strc_value<std::string>(strc_var.value, element_count); break;
    default: // invalid type -> maybe throw exception within python?!
}
{ 常量T*元素=重新解释(值); 对于(int offset=0;offset!=size;++offset) *(元素+偏移)//此时元素位于偏移+1位置 } 开关(strc_变量类型) { 案例0:迭代strc值(strc变量值、元素计数);中断; 案例1:迭代strc值(strc变量值、元素计数);中断; 案例2:迭代strc值(strc变量值、元素计数);中断; 默认值://无效类型->可能会在python中引发异常?! }
指针是您也命名为
的指针,而
大小
指定数组中的元素数量。不需要类型的大小,因为类型的大小在编译时是已知的

基本上,该函数只是将
void*
转换为所需类型的指针,然后使用指针算法在数组上迭代。这种方法非常通用,只要知道数组的大小,就可以迭代指向数组的任何
void*

您还可以添加第三个参数作为回调,它对每个元素执行给定的操作,以将专用代码保留在模板函数之外。

谢谢您的回答。我没有访问cpp代码的权限,因此我不确定是否可以使用此代码。我正在用ctypes加载已编译的库,并从中调用函数。@Presbitero,你在找这个吗?:
ctypes.cast(mystrc.value,ctypes.POINTER())
。然后可以将结果作为数组访问。而
指针
实际上是全大写的。(如果我按你说的做,例如
a=ctypes.cast(mystrc.value,ctypes.POINTER,ctypes.float))我会得到
非类型
打印mystrc.value
然后
a
给出了我不知道如何处理的
。如果我这样做
mystrc.value.contents
我会得到以下错误
回溯(最后一次调用):File“”,ValueError中的第1行:空指针访问
您可以使用下标操作符
a[index]
访问
a
。但是,正如Python告诉您,您正试图通过调用
contents
来取消对空指针的引用,我假设您的空指针实际上是一个空指针,并且不指向任何有效的内存区域。是否有
count
0