Skip to content Skip to sidebar Skip to footer

Accessing Contents Of An Object Returned By Dll Using Ctypes In Python

The dll returns an object on calling a function using ctypes in python. It returns the following - say it is named as ReturnO; print(ReturnO) gives the following: (63484,

Solution 1:

Given your description it looks like you have a C function similar to the following:

#include<inttypes.h>#define API __declspec(dllexport)structClassName
{
    float parameter_1[5];
    float parameter_2[5];
};

API int __stdcall Getoutput(int a, uint32_t b, uint32_t* pc, struct ClassName* pd){
    int i;
    *pc = a+b;
    for(i=0;i<5;++i)
    {
        pd->parameter_1[i] = i*.5f;
        pd->parameter_2[i] = i*.25f;
    }
    return a*b;
}

Your paramflags argument indicates two inputs (type 1) and two return values (type 2). Simply pass the two required input values, then index the second return value to access its members. Use list() to convert the array to Python lists:

from ctypes import *

class ClassName(Structure):
  _fields_ = [('parameter_1',c_float * 5),
              ('parameter_2',c_float * 5)]

lib = WinDLL('test')
prototype = WINFUNCTYPE(c_int,c_int,c_uint32,POINTER(c_uint32),POINTER(ClassName))
paramflags = (1,'int2'),(1,'num2'),(2,'num22'),(2,'str2')
Getoutput = prototype(('Getoutput',lib),paramflags)

ret = Getoutput(10,11)
print(ret)
print(ret[1].parameter_1)
print(ret[1].parameter_2)
print(list(ret[1].parameter_1))
print(list(ret[1].parameter_2))

Output:

(21, <__main__.ClassName object at 0x000001DA3A9139C8>)
<__main__.c_float_Array_5 object at 0x000001DA3A790EC8>
<__main__.c_float_Array_5 object at 0x000001DA3A790EC8>
[0.0, 0.5, 1.0, 1.5, 2.0]
[0.0, 0.25, 0.5, 0.75, 1.0]

Solution 2:

If you have a ctypes float array, there are various means to get each of the float.

Example:

We start with a simple python float list, just for the sake of the demo:

>>>python_float_list = [1.5, 2.5, 3.5, 4.5, 5.5]  

Create a ctypes float array from the list:

>>>import ctypes>>>c_float_array = (ctypes.c_float * 5)(*python_float_list)>>>c_float_array
<__main__.c_float_Array_5 object at 0x000001D6D9A66A48>

ctypes arrays are subscriptable:

>>>c_float_array[0]
1.5
>>>c_float_array[1]
2.5

You can use a for loop on them too:

>>> for f in c_float_array:
    print(f)


1.52.53.54.55.5

As the ctypes arrays are subscriptable, you can get a python list back from them:

>>> list(c_float_array)
[1.5, 2.5, 3.5, 4.5, 5.5]

Post a Comment for "Accessing Contents Of An Object Returned By Dll Using Ctypes In Python"