5

How can I pass null * array to a C function via ctypes?

 2 years ago
source link: https://www.codesd.com/item/how-can-i-pass-null-array-to-a-c-function-via-ctypes.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How can I pass null * array to a C function via ctypes?

advertisements

I have a C function in a dll file defined as follows:

myFunction(const int a, long b, void * data, unsigned int * c, unsigned int * d, unsigned long * timestamp)

Parameters:

[in]: a
[in]: b
[out]: data, which is a pointer to a buffer that is maximum of 8 bytes
[out]: c, points to a buffer that receives data message length
[out]: d, pointer to a buffer which receives a message flag
[out]: timestamp, pointer to a buffer which receives message timestamp

My python code is as follows:

import ctypes

dllhandle = ctypes.WinDLL("dllFile.dll")

a = 1
b = 1738
data = ctypes.c_void_p*8
c = 0
d = 0
timestamp = 0

dllhandle.myFunction(a, b, data, c, d, timestamp)

When I run my python code, I get the following error:

ctypes.ArgumentError: argument 3: <type 'exceptions.TypeError'>: Don't know how to convert parameter 3.

I figured this has to do with how I am creating my data buffer pointer array. What is the proper way of creating the data buffer?


You should use an array of chars to pass your data. I have written this script that could help you:

"""
extern "C" void your_func(void* buffer, int size);
"""
# For Python 2.7
import ctypes

BUFFER_SIZE = 256

# Importing dll
dll = ctypes.CDLL("dllFile.dll")

# Defining C-arguments and output
buffer_c_type = lambda chars: (ctypes.c_char * BUFFER_SIZE)(*map(ctypes.c_char, chars))
size_c_type = ctypes.c_int
restype = None # None is for 'void' as the result of your function in C

# Creating C-arguments having Python variables 'buffer' and 'BUFFER_SIZE'
buffer = "qwdeasdvwergb"
c_buffer = buffer_c_type(buffer)
c_size = size_c_type(BUFFER_SIZE)

# Extracting your_func from dll and setting the type of returning value
your_func = dll["your_func"]
your_func.restype = restype

# Running your_func
your_func(c_buffer, c_size)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK