将python列表传递给使用ctypes返回数组数据的“c”DLL函数

用户955566

我想将一个包含字符串数据的 python 列表传递给一个“c”DLL,它处理数据并返回一个包含整数数据的数组。使用“ctypes”的python代码和c代码是什么。我总结如下:

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

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

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

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

动态链接库

#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[]
}
马克·托洛宁

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

测试.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]);
}

测试文件

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]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章