passing arrays with ctypes

前端 未结 1 1583
粉色の甜心
粉色の甜心 2020-12-31 21:21

I have a C function

void read_FIFO_AI0(int16_t** input, size_t size, NiFpga_Session* session, NiFpga_Status* status)
{
  *input = (int16_t*) malloc (size*siz         


        
相关标签:
1条回答
  • 2020-12-31 22:04

    The first argument's type is POINTER(POINTER(c_int16)) not POINTER(ARRAY(c_int16,size)).

    Here's a short example:

    x.c (compiled with cl /LD x.c:

    #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

    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)
    

    Output:

    0
    1
    2
    3
    4
    

    Note this leaves you with potential memory leak if you don't remember to free the malloc. A better way would be to allocate the buffer in Python and tell the C function the size:

    x.c

    #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

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

    Output

    [0, 1, 2, 3, 4]
    
    0 讨论(0)
提交回复
热议问题