Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Call a MEX function from Matlab Engine?
Date: Thu, 13 Mar 2008 21:50:19 +0000 (UTC)
Organization: Boeing
Lines: 73
Message-ID: <frc7ir$s19$1@fred.mathworks.com>
References: <frc4bp$ipi$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-05-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1205445019 28713 172.30.248.35 (13 Mar 2008 21:50:19 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 13 Mar 2008 21:50:19 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 756104
Xref: news.mathworks.com comp.soft-sys.matlab:457139



"David Doria" <daviddoria@gmail.com> wrote in message 
<frc4bp$ipi$1@fred.mathworks.com>...
> I have a mex file test.mexw32 in
> 'C:\Documents and Settings\Dave\My Documents\Visual 
Studio
> 2005\Projects\Matlab MEX'
> 
> My function simply squares the input.  In matlab, test(4)
> tells me 16.
> 
> Now in my c++ code, I did this:
> 
> engEvalString(ep, "cd 'C:\Documents and Settings\Dave\My
> Documents\Visual Studio 2005\Projects\Matlab MEX';");
> 
> engEvalString(ep, "a=test(4);");
> mxArray *test2 = NULL;
> test2 = mxCreateDoubleMatrix(1, 1, mxREAL);
> test2 = engGetVariable(ep, "a");
> double *myout2;
> myout2 = mxGetPr(test2);
> cout << myout2[0] << endl;
> 
> I get a "Access violation reading location" error. What 
have
> I done wrong?
> 
> Thanks,
> 
> Dave

Comments:

1) You should reply to the original threads in this 
newsgroup rather than creating new ones. That way people 
can keep track of the original problem and the various 
solutions discussed along the way.

2) You don't list your mex file, so I don't know what it 
returns as an output. Does it work? Does it return a 
double, an integer? Try calling your mex file from MATLAB 
to verify this, e.g.

>> test(4)
>> class(ans)

If it is not a double class, then of course your mxGetPr 
call and the follow-on myout2[0] calculation can certainly 
cause an access violation. Your earlier thread posting 
indicated your MyFunc returned an integer. Is this what 
you are using?  In general, you should always check the 
class, number of elements, etc. of an mxArray before using 
it.

3) The first of these two lines is pointless:

> test2 = mxCreateDoubleMatrix(1, 1, mxREAL);
> test2 = engGetVariable(ep, "a");

Why? Because you first create a brand new mxArray and 
store a pointer to it in test2. Then you immediately wipe 
this pointer out with a brand new pointer to the mxArray 
returned by engGetVariable. This is a memory leak. You 
just wiped out your only handle to the heap memory 
allocated for the first double matrix you created. 
MATLAB's memory manager will fortunately clean this up for 
you when the mex file exits, but it is still bad.

4) I am assuming that the engine opened properly.

James Tursa