Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

Use function handle in MEX file (serialize it)

Asked by Szabolcs on 8 Apr 2013

What sorts of things can one do with a function handle in a MEX file?

What I'd like to do is extract all the relevant data from an mxArray that represents a function handle in such a way that I could create a different mxArray that will represent the same function handle.

In other words, I'd need to serialize an mxArray function handle.

I need this while building a bridge between MATLAB and another language. I would like to support classes in MATLAB. I can take apart just about any other kind of mxArray and put them back together as there exist mx* functions for these (e.g. mxGetData() for numerical arrays, etc.) So far it's only function handles I couldn't cope with.

EDIT: For this application I can always keep a dictionary of available function handles. I do not need or want to expose the underlying data (which may be a pointer, thus unsafe). But in order to keep a dictionary, I need to be able to at least compare function handles: do two mxArray refer to the same function handle?

0 Comments

Szabolcs

Products

1 Answer

Answer by James Tursa on 8 Apr 2013
Edited by James Tursa on 8 Apr 2013
Accepted answer

You might look into these undocumented API functions:

mxSerialize
mxDeserialize

I have never used them myself, but you can find some information here:

http://stackoverflow.com/questions/4807035/is-it-possible-to-intercept-a-matlab-save-bytestream

I have no idea how these functions would work for a function handle, which can have multiple embedded mxArray data buried within them.

How are you going to deal with classdef objects?

2 Comments

Szabolcs on 8 Apr 2013

There's some interesting info here as well: mxFunctionHandleToSavedStruct() and mxSavedStructToFunctionHandle()

James Tursa on 9 Apr 2013

I checked those function out and FYI they preserve the shared-data-copy-ness of the data (for lack of a better term). E.g., if you start with something like this:

A = rand(2);
f = @(x)(A*x);

the function handle f will have a shared-data-copy of A inside of it. If you subsequently use mxFunctionHandleToSavedStruct on f, the resulting struct will have a shared-data-copy of A as well. And likewise if you subsequently go through mxSavedStructToFunctionHandle also. All of these will have shared-data-copies of the workspace variables (in this case A) used in the function handle.

James Tursa

Contact us