Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Modifying MEX arguments in place?
Date: Thu, 14 Feb 2008 22:13:02 +0000 (UTC)
Organization: Boeing
Lines: 48
Message-ID: <fp2ede$j0a$1@fred.mathworks.com>
References: <fp0fqv$3gd$1@fred.mathworks.com> <muyir0r1v1p.fsf@G99-Boettcher.llan.ll.mit.edu>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1203027182 19466 172.30.248.37 (14 Feb 2008 22:13:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 14 Feb 2008 22:13:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 756104
Xref: news.mathworks.com comp.soft-sys.matlab:451503



Peter Boettcher <boettcher@ll.mit.edu> wrote in message 
<muyir0r1v1p.fsf@G99-Boettcher.llan.ll.mit.edu>...
> 
> The answer is to use the undocumented mxUnshareArray() 
before modifying
> the input.  We think the prototype is:
> 
> int mxUnshareArray(mxArray *, int);
> 
> We don't know what the second argument does.  Zero seems 
to do the trick.
> 
> 
> -Peter

If mxUnshareArray does what I think it does, which is make 
a copy of the data (if needed) and reset the data pointers 
to the new copy, then I disagree that this is *the* answer 
to OP's problem. OP is trying to avoid multiple copies of 
his data, not make new ones just so his mex routine can 
modify the data in place. For example, suppose A was a 2GB 
array and then you did B = A, and then you called the mex 
routine mymexroutine(B). What is the difference, memory 
usage wise, between calling mxUnshareArray(prhs[0]) and 
then modifying prhs[0] in place vs just calling plhs[0]
=mxDuplicateArray(prhs[0]) and then modifying plhs[0]? 
Nothing. You still get two copies of the 2GB data either 
way. I still think the best thing to do is be very careful 
on the MATLAB side to never do assignments or function 
calls that might result in data sharing *before* you call 
the mex routine. Then you can call mxUnshareArray inside 
the mex routine just to be safe. In those cases where you 
screwed up on the MATLAB side and the data was in fact 
shared, you would wind up paying the memory/speed penalty 
or maybe even exhaust the heap. But at least you would 
return with an error instead of screwing up other 
variables had you not called mxUnshareArray.

Do you know if mxUnshareArray behaves like other mx 
functions that allocate memory? i.e., if it fails in a mex 
routine does it free all memory allocated inside the mex 
routine and return control to MATLAB? And in an engine 
application if it fails does it return 1?

James Tursa