Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

python

c

dll

Background

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

  1. The bytes to be written are stored in variable name data
  2. The c function (in dll) which has to be called from python is

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

  3. I have no access to the dll code

Method tried

I tried to declare a data type

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

and called the 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 its not working. The API call works with C and C++.

Am I doing this correct. Could anyone please kindly point the mistake for me?

like image 952
Prajosh Premdas Avatar asked Sep 18 '15 13:09

Prajosh Premdas


1 Answers

What you try to achieve can be done like this.

Interface header, say functions.h

#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 simply 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 the number 37 printed on the screen.

like image 187
Jens Munk Avatar answered Sep 19 '22 08:09

Jens Munk