0

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?

3
  • 1
    Define c as "ctypes.c_char * 40" Commented Mar 18, 2021 at 0:25
  • @MichaelButscher 40 and not 41? (That works - make it an answer and I'll upvote it!) Commented Mar 18, 2021 at 0:26
  • 1
    Yes, the same length as in the C struct. Commented Mar 18, 2021 at 0:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.