简体   繁体   English

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

[英]python - ctypes, retrieve value of void pointer sent to shared c library

Im calling a cpp function from dll with ctypes 我从带有ctypes的dll调用cpp函数

the function definition is 函数定义是

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

And the structure: 以及结构:

typedef struct
{
    int type;
    int count;
    void *value;
} strc;

So what I tried in python was to define: 所以我在python中尝试的是定义:

class strc(ctypes.Structure):
    _fields_ = [('type', ctypes.c_int),
                ('count', ctypes.c_int),
                ('value', ctypes.c_void_p)]

And to call the function as 并将其称为

varsize = ctypes.c_int()
mystrc = strc()
foo(ctypes.byref(mystrc), ctypes.byref(varsize))

I can perfectly call the function and retrieve all values except for the "value". 我可以完美地调用该函数并检索除“值”之外的所有值。 It should be an array of variables indicated by the "type", have size "varsize" and be an array of "count" variables. 它应该是由“类型”指示的变量数组,大小为“ varsize”,并且应为“计数”变量数组。

How can I retrieve what is indicated by the void pointer? 如何检索void指针指示的内容?

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

The value pointer is the pointer that you also named value , while size specifies the amount of elements within the array. value指针是您也命名为value的指针,而size指定数组中元素的数量。 The size of the type is not needed, as the size of your types is known at compile time. 不需要类型的大小,因为在编译时就知道类型的大小。

Basically the function just converts the void* to a pointer of your desired type and then uses pointer arithmetic to iterate over the array. 基本上,该函数只是将void*转换为所需类型的指针,然后使用指针算术对数组进行迭代。 This approach is general enough to just iterate over any void* which points to an array as long as you know it's size. 只要您知道数组的大小,此方法就足以遍历指向数组的任何void* You could also add a third argument as a callback which performs the given action on each element to keep specialized code outside of the template function. 您还可以添加第三个参数作为回调,该回调对每个元素执行给定的操作,以将专用代码保留在模板函数之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM