Main Content

Integrate External Code That Uses Custom Data Types

This example shows how to call a C function that uses data types that are not natively defined within MATLAB®.

For example, if your C code performs file input or output on a C 'FILE *' type, there is no corresponding type within MATLAB. To interact with this data type in your MATLAB code, you must initialize it by using the function coder.opaque. In the case of structure types, you can use coder.cstructname.

For example, consider the MATLAB function addCTypes.m. This function uses coder.ceval with input types defined in external code. The function coder.opaque initializes the type in MATLAB.

function [out] = addCTypes(a,b)
%#codegen
% generate include statements for header files
coder.cinclude('MyStruct.h');
coder.cinclude('createStruct.h');
coder.cinclude('useStruct.h');
% initialize variables before use
in = coder.opaque('MyStruct');
out = 0;
% call C functions
in = coder.ceval('createStruct',a,b);
out = coder.ceval('useStruct',in); 
end


The createStruct function outputs a C structure type:

#include <stdio.h>
#include <stdlib.h>
#include "MyStruct.h"
#include "createStruct.h"

struct MyStruct createStruct(double a, double b) {
    struct MyStruct out;
    out.p1 = a;
    out.p2 = b;
    return out;
}

The useStruct function performs an operation on the C type:

#include "MyStruct.h"
#include "useStruct.h"

double useStruct(struct MyStruct in) {
    return in.p1 + in.p2;
}

To generate code, specify the source (.c) files as inputs:

codegen addCTypes -args {1,2} -report createStruct.c useStruct.c
Code generation successful: To view the report, open('codegen/mex/addCTypes/html/report.mldatx')