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

Thread Subject:
Can I replace malloc and cousins with mxMalloc etc. using #defines?

Subject: Can I replace malloc and cousins with mxMalloc etc. using #defines?

From: Richard Crozier

Date: 4 Sep, 2012 12:08:07

Message: 1 of 2

Hello,

I am wondering if it is possible to take some code written in standard C++ and C, and replace all calls to malloc and similar with calls to mxMalloc using preprocessor directives.

I have succesfully done this with mexPrintf, where I simply pass the following directive to the compiler when building the code as part of a mexfuntion:

-D"printf=mexPrintf"

This seems to work.

Can I safely do something similar such as:

#define malloc mxMalloc

to replace all calls to malloc with mxMalloc? The purpose of this would be so that I could attach a large dataset to a matlab array and return it as an argument from my mexfunction without copying memory. Will ints be cast to mwSize without issues?

I confess I haven't actually tried doing this yet, and haven't seen how the compiler reacts. I was just wondering if anyone has any thoughts on this?

Subject: Can I replace malloc and cousins with mxMalloc etc. using #defines?

From: James Tursa

Date: 5 Sep, 2012 17:11:07

Message: 2 of 2

"Richard Crozier" wrote in message <k24qv7$lrp$1@newscl01ah.mathworks.com>...
> Hello,
>
> I am wondering if it is possible to take some code written in standard C++ and C, and replace all calls to malloc and similar with calls to mxMalloc using preprocessor directives.
>
> I have succesfully done this with mexPrintf, where I simply pass the following directive to the compiler when building the code as part of a mexfuntion:
>
> -D"printf=mexPrintf"
>
> This seems to work.
>
> Can I safely do something similar such as:
>
> #define malloc mxMalloc
>
> to replace all calls to malloc with mxMalloc? The purpose of this would be so that I could attach a large dataset to a matlab array and return it as an argument from my mexfunction without copying memory. Will ints be cast to mwSize without issues?
>
> I confess I haven't actually tried doing this yet, and haven't seen how the compiler reacts. I was just wondering if anyone has any thoughts on this?

The pre-processor runs before the compiler itself sees the code, so you should be able to define malloc to be mxMalloc. But I think you will need to show an example of how you plan to stuff the result into a MATLAB return variable before we can comment on what errors, if any, you might have.

James Tursa

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us