用C表示单元阵列(来自MATLAB)



问题:如何在Cell数组和独立的Matrix对象之间设计更好的接口?

我正在将一个使用单元格数组和单元格数组的单元格数组的MATLAB代码转换为C。我创建了一个Matrix数据类型和一个cell数据类型。它们如下图所示。

Matrix数据类型

typedef struct{
  double * array; // row major format
  int rows;
  int cols;
} Matrix;

和Cell数据类型

typedef struct{
  Matrix * array; // row major format
  int rows;
  int cols;
} Cell;

幸运的是,代码中的单元格数组是一个简单的一维单元格数组,我可以将其表示为单元格对象的数组。

在原始代码中,独立的矩阵对象和单元数组(另一个矩阵)的元素一起出现在表达式中。例如:

a = rand(10);
% say, b is a cell array containing other matrices
% c = some expression involving an element of the cell array b and a
c = a + b{1,2};
% assuming dimensions agree

现在,在我的表示中,当我创建一个单元格对象时,我已经分配了矩阵对象的行*cols,并将指向矩阵对象数组的指针分配给数组(单元格内)。假设矩阵对象在代码的后面(使用它们之前)进行了适当的初始化

我动态分配的独立矩阵对象是通过取消引用指向它们的指针来访问的,单元数组的访问器例程返回矩阵对象,而不是指向矩阵对象的指针。

// Function signature for accessor routine of cell object 
Matrix get_mat_from_cell(Cell * cell, int row, int col);
// Independent Matrix object - dynamically allocated as size is known
// at run-time
Matrix * matrixA = (Matrix *) malloc(sizeof(Matrix));
Matrix matrixB = get_mat_from_cell(someCell, 1, 2);
add(matrixA, &matrixB, matrixC); // adds matrixA, matrixB and stores in a matrixC

让我高兴的是在add函数中(例如),要获得一个统一的接口,接受所有3个参数的矩阵指针,我必须传递matrixB的地址。它要么在函数接口级别上看起来是一致的,比如add(Matrix*、Matrix*和Matrix*),要么在函数调用级别上是一致的——add(Matric*、Matric*和Matric*),而不是双向的。

我可以通过将Cell对象内的数组声明为双指针来实现一致性,但在到达Matrix对象之前,我必须取消引用两次,并想知道这是否会成为性能瓶颈,因为这些单元格非常大,而且经常被访问。

如何更好地设计此界面?

谢谢。

看起来你已经解决了这个问题,但无论如何我都会尽力伸出援手。首先,我认为您的Cell结构需要调整,除非您知道您的实现是非常具体的

/* small set of types as example */
typedef union matlab_fundamental_types_u
{
  CELL,
  MATRIX
} matlab_fundamental_types_t;
typedef struct Cell_s
{
  struct Cell_s * array; // row major format
  matlab_fundamental_types_t fundamental_type; /* what this cell holds, is it a cell of cells, arrays, etc? */
  int rows;
  int cols;
} Cell;

由于Cell是一个超级容器,可以容纳任何东西,包括Cell,因此以这种方式实现它是有意义的,尽管我认为它仍然需要一些修饰。此外,您还提到了双指针取消引用是一个瓶颈的问题。我想我不会担心的。我的经验是,malloc、免费的文件操作是真正的瓶颈,但唯一可以确定的方法是探查器。希望这能有所帮助!

最新更新