Path: news.mathworks.com!newsfeed-00.mathworks.com!panix!bloom-beacon.mit.edu!llnews!53ab2750!not-for-mail
From: Peter Boettcher <boettcher@ll.mit.edu>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Modifying MEX arguments in place?
References: <fp0fqv$3gd$1@fred.mathworks.com>
Message-ID: <muyir0r1v1p.fsf@G99-Boettcher.llan.ll.mit.edu>
Organization: MIT Lincoln Laboratory
User-Agent: Gnus/5.110006 (No Gnus v0.6) Emacs/23.0.0 (gnu/linux)
Cancel-Lock: sha1:+upKM5runFWWZMoXVabijmPBNTk=
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Lines: 38
Date: Thu, 14 Feb 2008 09:17:54 -0500
NNTP-Posting-Host: 155.34.163.114
X-Complaints-To: news@ll.mit.edu
X-Trace: llnews 1202998144 155.34.163.114 (Thu, 14 Feb 2008 09:09:04 EST)
NNTP-Posting-Date: Thu, 14 Feb 2008 09:09:04 EST
Xref: news.mathworks.com comp.soft-sys.matlab:451386



"Petr Krysl" <pkryslNOSP@Mucsd.edu> writes:

> roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote in
> message <fp0gke$gqq$1@canopus.cc.umanitoba.ca>...
>> I know little about MEX, but generally speaking, the memory
>> that you are handed for any Matlab variable might be shared
>> with other Matlab variables due to the "lazy copy" behaviour.
>> The columns you see might be linked to columns of other
> variables.
>> When you change the memory in-place, you would have
> changed those
>> other variables too.
>
> I am not sure I follow: I can certainly access the
> individual elements of the array that I want to modify by
> read-access (and I see the right data). Why can't I write
> into the same memory locations? I understand that I might be
> modifying a copy of the input argument, but that does not
> seem to be the case. Actually, when I look at the matrix
> after I've modified the input argument and returned from the
> mex file, the matrix contains correctly modified data. 
> Unfortunately something else seems to have been affected,
> and the Matlab interpreter stops working correctly.

First generate a dataset.  Then do b=a;  (Copy the dataset).  Then run
your in-place code on "a".  Then look at b.  That's the problem. 

This can happen in strange places if you're not careful.

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