首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ctype传递数组

使用ctype传递数组
EN

Stack Overflow用户
提问于 2014-10-09 19:31:46
回答 1查看 14.5K关注 0票数 7

我有一个C函数

代码语言:javascript
复制
void read_FIFO_AI0(int16_t** input, size_t size, NiFpga_Session* session, NiFpga_Status* status)
{
  *input = (int16_t*) malloc (size*sizeof(int16_t));
  // function that populates the array *input
}

它填充数组"*input“。现在,我希望将该数组中的数据传递给python进行进一步处理。我尝试使用ctype来做到这一点:

代码语言:javascript
复制
def read_FIFO_AI0(size,session,status):
    _libfpga.read_FIFO_AI0.argtypes = [POINTER(ARRAY(c_int16, size)), c_int, POINTER(c_uint32), POINTER(c_int32)]
    _libfpga.read_FIFO_AI0.restype = None

    values = (c_int16*size)()
    _libfpga.read_FIFO_AI0(byref(values),size,byref(session),byref(status))
    return values

代码执行了,但我在数组中得到了错误的结果。当我尝试在C中使用C函数时,我得到了正确的结果:

代码语言:javascript
复制
size_t size=20;
int16_t* input;

read_FIFO_AI0(&input, size, &session, &status);

什么是填充数组的正确方法,以便我可以访问Python中的数据?我不局限于使用指向填充的数组的指针,我也可以在C函数中创建数组并将其作为返回发送到Python,但我也没有开始工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-11 12:25:53

第一个参数的类型是POINTER(POINTER(c_int16)),而不是POINTER(ARRAY(c_int16,size))

下面是一个简短的示例:

x.c (使用cl /LD x.c编译

代码语言:javascript
复制
#include <stdlib.h>
#include <stdint.h>
__declspec(dllexport) void read(int16_t** input, size_t size)
{
  int i;
  int16_t* p = (int16_t*) malloc (size*sizeof(int16_t));
  for(i=0;i<size;i++)
    p[i] = i;
  *input = p;
}
__declspec(dllexport) void release(int16_t* input)
{
    free(input);
}

x.py

代码语言:javascript
复制
from ctypes import *
x = CDLL('x')
x.read.argtypes = POINTER(POINTER(c_int16)),c_size_t
x.read.restype = None
x.release.argtypes = [POINTER(c_int16)]
x.release.restype = None
p = POINTER(c_int16)()
x.read(p,5)
for i in range(5):
    print(p[i])
x.release(p)

输出:

代码语言:javascript
复制
0
1
2
3
4

注意:如果您不记得对malloc执行free操作,这会给您留下潜在的内存泄漏。更好的方法是在Python中分配缓冲区,并告诉C函数大小:

x.c

代码语言:javascript
复制
#include <stdlib.h>
#include <stdint.h>
__declspec(dllexport) void read(int16_t* input, size_t size)
{
  int i;
  for(i=0;i<size;i++)
    input[i] = i;
}

x.py

代码语言:javascript
复制
from ctypes import *
x = CDLL('x')
x.read.argtypes = POINTER(c_int16),c_size_t
x.read.restype = None
p = (c_int16*5)()
x.read(p,len(p))
print(list(p))

输出

代码语言:javascript
复制
[0, 1, 2, 3, 4]
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26277322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档