How to pass a python list to a C (dll) function using ctypes

Background

I have analysis software in Python. I have to pass a list of 4096 bytes (which looks like this [80, 56, 49, 50, 229, 55, 55, 0, 77, ......] ) in the dll so that the DLL writes it to the device.

  • Bytes to be written are stored in the variable name data
  • The c function (in the dll) that should be called from python,

    int _DLL_BUILD_ IO_DataWrite(HANDLE hDevice, unsigned char* p_pBuff, unsigned char p_nByteCntInBuff);

  • I do not have access to the dll code

I tried the method

I tried to declare a data type

 data_tx = (ctypes.c_uint8 * len(data))(*data) 

and is called a function

 ret = self.sisdll.IO_DataWrite(self.handle, ctypes.byref(data_tx), ctypes.c_uint8(pending_bytes)) 

Problem

There seems to be no error, but it does not work. The API call works with C and C ++.

I am doing it right. Can someone please point me to the error?

+5
source share
1 answer

What you are trying to achieve can be done as follows.

The title of the interface, say, the .h function

 #include <stdint.h> #include "functions_export.h" // Defining FUNCTIONS_API FUNCTIONS_API int GetSomeData(uint32_t output[32]); 

C source, functions.c

 #include "functions.h" int GetSomeData(uint32_t output[32]) { output[0] = 37; } 

In python you just write

 import ctypes hDLL = ctypes.cdll.LoadLibrary("functions.dll") output = (ctypes.c_uint32 * 32)() hDLL.GetSomeData(ctypes.byref(output)) print(output[0]) 

You should see number 37 printed on the screen.

+5
source

All Articles