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

2024-05-01 17:58:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我用ctypes从dll调用cpp函数

函数定义是

int foo(strc *mystrc, int *varsize);

以及结构:

^{pr2}$

所以我在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指针所指示的内容?在


Tags: 函数定义foovaluetypecount数组ctypes
1条回答
网友
1楼 · 发布于 2024-05-01 17:58:55
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?!
}

value指针是您也命名为value的指针,而size指定数组中元素的数量。不需要类型的大小,因为类型的大小在编译时是已知的。在

基本上,该函数只需将void*转换为所需类型的指针,然后使用指针算法在数组上迭代。这种方法足够通用,只要知道数组的大小,就可以遍历任何指向数组的void*。 您还可以添加第三个参数作为回调函数,它对每个元素执行给定的操作,以将专用代码保留在模板函数之外。在

相关问题 更多 >