I want to pass a python list containing string data to a "c" DLL, which process the data and should return an array containing integer data. What will be the python code and c code using "ctypes". I summarize it as follows:
I want to pass following data from python script, e.g:
`list=["AO10","AO20","AO30"]` and
i expect that DLL code should return an array of integers, e.g
arr={10,20,30}
I have tried the following code but the program halted without giving any data
from ctypes import *
mydll = CDLL("C:\\abc.dll")
mydll.sumabc.argtypes = (POINTER(c_char_p), c_int)
list= ["AO10","AO20","AO30"]
array_type = c_char_p * 3
mydll.sumabc.restype = None
my_array = array_type(*a)
mydll.epicsData(my_array, c_int(3))
print(list(my_array))
#include "stdafx.h"
#include "myheader.h"
int* epicsData(char *in_data, int size)
{
for(int i = 1; i < size; i++)
{
in_data[i] =i*10;
}
return in_data[]
}
The given C code doesn't match the Python wrapper. The function name doesn't match and the types don't match. Here's a working example for your learning:
test.c
#include <string.h>
#ifdef _WIN32
# define API __declspec(dllexport) // Windows-specific export
#else
# define API
#endif
/* This function takes pre-allocated inputs of an array of byte strings
* and an array of integers of the same length. The integers will be
* updated in-place with the lengths of the byte strings.
*/
API void epicsData(char** in_data, int* out_data, int size)
{
for(int i = 0; i < size; ++i)
out_data[i] = (int)strlen(in_data[i]);
}
test.py
from ctypes import *
dll = CDLL('test')
dll.epicsData.argtypes = POINTER(c_char_p),POINTER(c_int),c_int
dll.epicsData.restype = None
data = [b'A',b'BC',b'DEF'] # Must be byte strings.
# Create the Python equivalent of C 'char* in_data[3]' and 'int out_data[3]'.
in_data = (c_char_p * len(data))(*data)
out_data = (c_int * len(data))()
dll.epicsData(in_data,out_data,len(data))
print(list(out_data))
Output:
[1, 2, 3]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments