Use Function Type Arguments - MATLAB & Simulink (original) (raw)

Main Content

MATLABĀ® supports C++ signatures with std::function and C function pointer arguments. Both std::function and C function pointer are_function types_ in MATLAB. C function pointers and std::function are not supported as function return types or data members.

Function Types

using funcPtrType = std::function<void(int*,int)>;  
void task(int *arr, int len , funcPtrType fp){  
    fp(arr, len);  
}  

You can specify clib.libname.funcPtrType as a function type. The MATLAB signature for task is:
clib.libname.task(clib.array.libname.Int,clib.libname.funcPtrType)

void task1((void (*param)(int));  
void task2((void (*param)(long));  

The MATLAB signatures for the functions are:
clib.libname.task1(clib.type.libname.Function1)
clib.libname.task2(clib.type.libname.Function2)

Call C++ Functions With Function Type Input

Pass C++ Library Function

You can use the double_inputoutput function defined in this header file to pass as input to function type argument in callFunc_inputoutput to manipulate an array. You can do this by creating a MATLAB function handle todouble_inputoutput.

#include <functional>
void double_inputoutput( int * arr, int len){
       for(int i=0;i<len;++i){
               arr[i] = arr[i]*2;
       }
}
using funcPtrType = std::function<void(int*,int)>;
void callFunc_inputoutput(int *arr, int len , funcPtrType fp){
       fp(arr, len);
}

Call callFunc_inputoutput with thedouble_inputoutput function.

fp = @clib.test2.double_inputoutput; arr = [1,2,3,4,5,6]; clib.test2.callFunc_inputoutput(arr,fp)

Help for Function

help clib.test2.double_inputoutput

clib.test2.double_inputoutput Representation of C++ function double_inputoutput.

arr = clib.test2.double_inputoutput(arr) Input Arguments arr vector int32

Output Arguments
  arr            vector int32  

Choose Input Function to Function Type

The MATLAB help function on function type displays a list of functions in your library that are compatible with your function type.

help clib.test2.funcPtrType

Accepted input for clib.test2.funcPtrType is a handle to a C++ library function with matching signature. C++ library functions with matching inputs and outputs to the C++ function type: @clib.test2.double_inputoutput

See Also

addFunctionType