jankos
jankos

Reputation: 916

python using ctypes to work with dll - structure OUT argument

In the header file of the dll I have the following structure

typedef struct USMC_Devices_st{
DWORD NOD;          // Number of the devices ready to work

char **Serial;      // Array of 16 byte ASCII strings
char **Version;     // Array of 4 byte ASCII strings
} USMC_Devices;         // Structure representing connected devices

I would like to call a dll function: DWORD USMC_Init( USMC_Devices &Str );

I tried with this:

class USMCDevices(Structure):
   _fields_ = [("NOD", c_long),
            ("Serial", c_char_p),
            ("Version", c_char_p)]

usmc = cdll.USMCDLL #this is the dll file
init = usmc.USMC_Init
init.restype = c_int32; # return type
init.argtypes = [USMCDevices]; # argument
dev = USMCDevices()
init(dev)

I get an error here. I guess the problem is with "Serial" and "Version" which both are array corresponding to the NOD (number of devices).

Any ideas how to solve this problem?

I really appreciate your help!!!

Upvotes: 1

Views: 2678

Answers (1)

Eryk Sun
Eryk Sun

Reputation: 34260

Use POINTER(c_char_p) for the char ** pointers. Indexing Serial or Version creates a Python string for the given null-terminated string. Note that indexing in the array beyond NOD - 1 either produces garbage values or will crash the interpreter.

C:

#include <windows.h>

typedef struct USMC_Devices_st {
    DWORD NOD;       // Number of the devices ready to work
    char **Serial;   // Array of 16 byte ASCII strings
    char **Version;  // Array of 4 byte ASCII strings
} USMC_Devices;

char *Serial[] = {"000000000000001", "000000000000002"};
char *Version[] = {"001", "002"};

__declspec(dllexport) DWORD USMC_Init(USMC_Devices *devices) {

    devices->NOD = 2;
    devices->Serial = Serial;
    devices->Version = Version;

    return 0;
}

// build: cl usmcdll.c /LD

Python:

import ctypes
from ctypes import wintypes

class USMCDevices(ctypes.Structure):
    _fields_ = [("NOD", wintypes.DWORD),
                ("Serial", ctypes.POINTER(ctypes.c_char_p)),
                ("Version", ctypes.POINTER(ctypes.c_char_p))]

usmc = ctypes.cdll.USMCDLL
init = usmc.USMC_Init
init.restype = wintypes.DWORD
init.argtypes = [ctypes.POINTER(USMCDevices)]
dev = USMCDevices()
init(ctypes.byref(dev))

devices = [dev.Serial[i] + b':' + dev.Version[i]
           for i in range(dev.NOD)]
print('\n'.join(d.decode('ascii') for d in devices))

Output:

000000000000001:001
000000000000002:002

Upvotes: 2

Related Questions