Main Content

coder.ref

指示要传引用的数据

说明

示例

coder.ref(arg) 表示 arg 是要传引用给外部 C/C++ 函数的表达式或变量。只能在 coder.ceval 调用中使用 coder.ref。C/C++ 函数可以读取或写入按引用传递的变量。为您要按引用传递到函数的每个参数使用一个单独的 coder.ref 构造。

另请参阅 coder.rrefcoder.wref

coder.ref(arg,'gpu') 指示 arg 是 GPU 参数。此选项需要有效的 GPU Coder™ 许可证。如果 coder.ceval 调用 CUDA® GPU __device__ 函数,代码生成器将忽略 'gpu' 设定。

示例

按引用传递标量变量

假设有 C 函数 addone,它返回输入加 1 之后的值:

double addone(double* p) {
  return *p + 1;
}

C 函数将输入变量 p 定义为指向一个双精度数的指针。

通过引用将输入传递给 addone

...
y = 0;
u = 42;
y = coder.ceval('addone', coder.ref(u));
...

按引用传递多个参数

...
u = 1;
v = 2; 
y = coder.ceval('my_fcn', coder.ref(u), coder.ref(v));
...

按引用传递类属性

...
x = myClass;
x.prop = 1;
coder.ceval('foo', coder.ref(x.prop));
...

按引用传递结构体

要指示结构体类型在 C 头文件中定义,请使用 coder.cstructname

假设有一个 C 函数 incr_struct。此函数可读取和写入输入参数。

#include "MyStruct.h"

void incr_struct(struct MyStruct *my_struct)
{
  my_struct->f1 =  my_struct->f1 + 1;
  my_struct->f2 =  my_struct->f2 + 1;
}

C 头文件 MyStruct.h 定义名为 MyStruct 的结构体类型:

#ifndef MYSTRUCT
#define MYSTRUCT

typedef struct MyStruct
{
    double f1;
    double f2;
} MyStruct;

void incr_struct(struct MyStruct *my_struct);

#endif

在 MATLAB® 函数中,通过引用向 incr_struct 传递一个结构体。要指示 s 的结构体类型具有在 C 头文件 MyStruct.h 中定义的名称 MyStruct,请使用 coder.cstructname

function y = foo
%#codegen
y = 0;
coder.updateBuildInfo('addSourceFiles','incr_struct.c');

s = struct('f1',1,'f2',2);
coder.cstructname(s,'MyStruct','extern','HeaderFile','MyStruct.h');
coder.ceval('incr_struct', coder.ref(s));

要生成独立库代码,请输入:

codegen -config:lib foo -report

按引用传递结构体字段

...
s = struct('s1', struct('a', [0 1]));
coder.ceval('foo', coder.ref(s.s1.a));
...

您也可以传递结构体数组的元素:

...
c = repmat(struct('u',magic(2)),1,10);
b = repmat(struct('c',c),3,6);
a = struct('b',b);
coder.ceval('foo', coder.ref(a.b(3,4).c(2).u));
...

输入参数

全部折叠

要按引用传递给外部 C/C++ 函数的参数。参数不能是类、System object™、元胞数组或元胞数组的索引。

数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char | struct
复数支持:

限制

  • 不能按引用传递以下数据类型:

    • 类或 System object

    • 元胞数组或元胞数组索引

  • 如果某属性具有 get 方法、set 方法或验证器,或者是具有某些特性的 System object 属性,则您不能按引用将该属性传递给外部函数。请参阅Passing By Reference Not Supported for Some Properties

提示

  • 如果 arg 是数组,则 coder.ref(arg) 提供数组第一个元素的地址。coder.ref(arg) 函数不包含有关数组大小的信息。如果 C 函数需要知道数据的元素数量,请将该信息作为单独的参数进行传递。例如:

    coder.ceval('myFun',coder.ref(arg),int32(numel(arg));
    
  • 当您按引用向外部 C/C++ 函数传递结构体时,可以使用 coder.cstructname 提供在 C 头文件中定义的 C 结构体类型的名称。

  • 在 MATLAB 中,coder.ref 会导致错误。要参数化您的 MATLAB 代码以使代码能够在 MATLAB 以及生成的代码中运行,请使用 coder.target

  • 您可以使用 coder.opaque 来声明传递给外部 C/C++ 函数以及从该函数传回的变量。

扩展功能

C/C++ 代码生成
使用 MATLAB® Coder™ 生成 C 代码和 C++ 代码。

GPU 代码生成
使用 GPU Coder™ 为 NVIDIA® GPU 生成 CUDA® 代码。

版本历史记录

在 R2011a 中推出