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)


[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)

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

本文标题:How can I pass null &amp;ast; array to a C function via ctypes&amp;quest; ...

技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(174)