0
votes

I'm trying to call a DLL function using ctypes. I need to pass the DLL function a pointer to C structure which the function will write to.

The C struct looks something like this:

struct foo {
   int a;
   float b;
   char c[40];
}

I'm stuck on how to define 'c'. I've got this in Python:

import ctypes

lib = ctypes.cdll.LoadLibrary(path_to_dll)

class foo(ctypes.Structure):
    _fields_ = [('a', ctypes.c_int), 
                ('b', ctypes.c_float),
                ('c', ctypes.create_string_buffer(41))] # 41 allows for terminating zero

abc = foo()
pABC = ctypes.byref(abc)
lib.dllFunction(pABC)

print(abc.a, abc.b, abc.c)

That almost works, but I get TypeError: second item in _fields_ tuple (index 3) must be a C type

How should I be defining the 'c' element of the structure?

1
Define c as "ctypes.c_char * 40" - Michael Butscher
@MichaelButscher 40 and not 41? (That works - make it an answer and I'll upvote it!) - nerdfever.com
Yes, the same length as in the C struct. - Michael Butscher

1 Answers

1
votes

A C array of fixed element count translates to Python-ctypes as the ctypes type (fundamental or a structure, union or even an array type) multiplied with the element count.

The result of the multiplication is a new array type which can be used e. g. in structures or to create a new array in memory.

In the specific case here char c[40] translates as a type to ctypes.c_char * 40.