c struct的Python ctypes定义

Tre*_*nam 8 python ctypes matlab-coder

我试图调用Matlab编码器生成的一些c代码.Matlab使用名为emxArray的ac结构来表示矩阵(在此处记录:http://www.mathworks.co.uk/help/fixedpoint/ug/c-code-interface-for-unbounded-arrays-and-structure-fields.html).

struct emxArray_real_T
{
    double *data;
    int *size;
    int allocatedSize;
    int numDimensions;
    boolean_T canFreeData;
};
Run Code Online (Sandbox Code Playgroud)

我几乎没有经验ctypes,我正在努力创建一个等效的结构,然后我可以使用它来传递向量来回传递给c .so中定义的函数.

这是我到目前为止在python中的地方......

class EmxArray(ctypes.Structure):
    """ creates a struct to match emxArray_real_T """

    _fields_ = [('data', ctypes.POINTER(ctypes.c_double)),
                ('size', ctypes.POINTER(ctypes.c_int)),
                ('allocatedSize', ctypes.c_int),
                ('numDimensions', ctypes.c_int),
                ('canFreeData', ctypes.c_bool)]    
Run Code Online (Sandbox Code Playgroud)

但是,如果我定义这个:

data = (1.1, 1.2, 1.3, 1.4)
L = len(data)

x = EmxArray()
x.data = (ctypes.c_double * L)(*data)
x.data = (ctypes.c_int * 1)(L)    
Run Code Online (Sandbox Code Playgroud)

这可行

print len(x.data[:L]) 

for v in x.data[:L]: print v
Run Code Online (Sandbox Code Playgroud)

编辑:我已整理并采纳了Roland的建议,并可以使用提取数据

data_out = x.data[:L]
Run Code Online (Sandbox Code Playgroud)

我需要进一步调查,看看我是否可以成功地使用这个结构来传递和接收来自c代码的数据.

按照Roland的建议实现ctypes结构不起作用 - 返回的值是垃圾,我从来没有弄清楚为什么我在追求基于python的lilbil回答的实现.我接受了答案,因为它最接近......

我会在这里记录我的解决方案,因为这可能会让别人浪费尽可能多的时间.

首先,我生成了一个简单的matlab函数,它将函数的每个元素自身相乘,并使用编码器将其编译为ac .so.这是使用ctypes导入到python.代码如下......

import ctypes

LIBTEST = '..../dll/emx_test/'
EMX = ctypes.cdll.LoadLibrary(LIBTEST + 'emx_test.so')
init = EMX.emx_test_initialize()

# Create a data structure to hold the pointer generated by emxCreateWrapper...
class Opaque(ctypes.Structure):
    pass

# make some random data to pass in
data_in = [1., 2., 4., 8., 16.]
L = len(data_in)
# create an empty array of the same size for the output
data_ou = [0] * L

# put this in a ctypes array
ina = (ctypes.c_double * L)(*data_in)
oua = (ctypes.c_double * L)(*data_ou)
# create a pointer for these arrays & set the rows and columns of the matrix
inp = ctypes.pointer(ina)
oup = ctypes.pointer(oua)

nrows = ctypes.c_int(1)
ncols = ctypes.c_int(L)

# use EMX.emxCreateWrapper_real_T(double *data, int rows, int cols) to generate an emx wrapping the data 
# input arg types are a pointer to the data NOTE its not great to have to resize the ctypes.c_double but cant see another way
EMX.emxCreateWrapper_real_T.argtypes = [ctypes.POINTER(ctypes.c_double * L), ctypes.c_int, ctypes.c_int]
# a pointer to the emxArray is returned and stored in Opaque
EMX.emxCreateWrapper_real_T.restype = ctypes.POINTER(Opaque)
# use emxCreateWrapper
in_emx = EMX.emxCreateWrapper_real_T(inp, nrows, ncols)
ou_emx = EMX.emxCreateWrapper_real_T(oup, nrows, ncols)

# so now we have to emx's created and have pointers to them we can run the emx_test
# emx test looks like this in matlab
#
# function res = emx_test ( in )
#     res = in .* in;
# end
#
# so basically it multiplies each element of the matrix by itself
# 
# therefore [1., 2., 4., 8., 16.] should become [1., 4., 8., 64., 256.]

EMX.emx_test(in_emx, ou_emx)

# and voila...that's what we get
print 'In: ', ina[:L]
print 'Out:', oua[:L]
Run Code Online (Sandbox Code Playgroud)

输出:

In: [1.0, 2.0, 4.0, 8.0, 16.0]
Out:[1.0, 4.0, 16.0, 64.0, 256.0]
Run Code Online (Sandbox Code Playgroud)

感谢大家的时间和建议.

Rol*_*ith 8

只需创建一个指针,然后分配数据;

import ctypes

class EmxArray(ctypes.Structure):
    """ creates a struct to match emxArray_real_T """

    _fields_ = [('data', ctypes.POINTER(ctypes.c_double)),
                ('size', ctypes.POINTER(ctypes.c_int)),
                ('allocatedSize', ctypes.c_int),
                ('numDimensions', ctypes.c_int),
                ('canFreeData', ctypes.c_bool)]

data = (1.3, 3.5, 2.7, 4.1)
L = len(data)

e = EmxArray()
e.data = (ctypes.c_double * L)(*data)
e.size = (ctypes.c_int * 1)(L)
# et cetera
Run Code Online (Sandbox Code Playgroud)


Rya*_*ton 3

我不太熟悉 Python-C 接口,所以我的建议可能不太理想。我的猜测是,崩溃可能是因为x->data从未初始化并且它指向的内存未分配。

在存在参数的情况下与其他语言的 MATLAB Coder 生成的代码进行交互时,我采用的方法emxArray是手动编写一个提供更简单 API 的 C 接口函数。emxArray这减轻了需要在其他环境(在我的特定情况下为 Android Java)中构建的负担。如果生成的函数foo接受并返回一个二维double数组,那么类似下面的代码就可以工作:

void foo(double *x, int *szx, double **y, int *szy);
Run Code Online (Sandbox Code Playgroud)

该函数将获取一个指向输入数据及其大小的指针,并提供一个指向输出数据及其大小的指针。实现看起来像这样:

void foo(double *x, int *szx, double **y, int *szy) 
{
  emxArray_real_T *pEmx;
  emxArray_real_T *pEmy;

  /* Create input emxArray assuming 2-dimensional input */
  pEmx = emxCreateWrapper_real_T(x, szx[0], szx[1]);

  /* Create output emxArray (assumes that the output is not */
  /* written before allocation occurs) assuming 2-D output  */
  pEmy = emxCreateWrapper_real_T(NULL, 0, 0);

  /* Call generated code (call foobar_initialize/terminate elsewhere) */
  foobar(pEmx, pEmy);

  /* Unpack result - You may want to MALLOC storage in *y and */
  /* MEMCPY there alternatively                               */
  *y = pEmy->data;
  szy[0] = pEmy->size[0];
  szy[1] = pEmy->size[1];

  /* Clean up any memory allocated in the emxArrays (e.g. the size vectors) */
  emxDestroyArray_real_T(pEmx);
  emxDestroyArray_real_T(pEmy);
}
Run Code Online (Sandbox Code Playgroud)

您应该能够更简单地从 Python 调用此函数并根据需要传入所需的数据。

我的另一个答案emxArray_*有关文件中找到的函数的更多详细信息foobar_emxAPI.h