matlabmatlab-codercode-generation

Can MATLAB Coder generate a function that takes a pointer as input?


I would like to use MATLAB Coder to generate an executable (or a function in an object file) that accepts a pointer to an array as an input.

I used libpointer to create a pointer object and then tried to compile with the following codegen command:

codegen -config:lib foo -args {coder.typeof(pointer_object_name)}

The resulting error message reported that coder.typeof does not support the lipointer type.

My ultimate goal is to create something that can be called from another C function, with no MATLAB in sight, and receive a pointer to an array as an input. Can MATLAB Coder generate something like that?


@ryan-livingston asked for the signature of the function I would like MATLAB Coder to generate.

Suppose that samples is a pointer to an array of floats. I think I want MATLAB Coder to create a void foo(float *samples) that performs various computations on those floats and perhaps writes results to a file or socket.

Now that I have the attention of @ryan-livingston, I suppose I should ask the following.


Solution

  • If you just generate code with a fixed-size array input, the generated code will be able to accept a pointer. For example:

    function x = foo(x)
    x = 2*x;
    % You can use MATLAB fopen, fprintf, fwrite here to write x to a file
    
    >> codegen foo -args zeros(10,20) -config:lib -report
    

    produces the interface:

    void foo(double x[200]);
    

    which is the same as:

    void foo(double *x);
    

    because of array to pointer decay on calls in C.

    Note that I've used the x = foo(x) syntax to have Coder pass x by reference to foo. Functions declared with the same variable as both input and output generally produce pass by reference when also called with the same variable as input and output at the callsite.