使用 ctypes 将 python 列表传递给 "c" DLL 函数,其中 returns 数组数据

Passing a python list to "c" DLL function which returns array data using ctypes

我想将包含字符串数据的 python 列表传递给 "c" DLL,它处理数据并且应该 return 包含整数数据的数组。 python 代码和使用 "ctypes" 的 c 代码是什么?我总结如下:

我想从 python 脚本传递以下数据,例如:

`list=["AO10","AO20","AO30"]` and

我希望 DLL 代码应该 return 一个整数数组,例如

arr={10,20,30}  

我试过下面的代码,但程序没有给出任何数据就停止了

Python 脚本

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

c DLL

#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[]
}

ChristiFati 的 问题下解决了我的问题:

How do you expect the func to return an int*, whan you're setting mydll.sumabc.restype = None. Try mydll.sumabc.restype = POINTER(c_int). And don't ignore the function's return value. Also, you can delete .

给定的 C 代码与 Python 包装器不匹配。函数名称不匹配且类型不匹配。这是供您学习的工作示例:

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

输出:

[1, 2, 3]