Will Matlab respond exceptions raised from VS compiled DLL? - matlab

Here's a brief summary for what happened: basically, I'm trying to rewrite a MATLAB program to a C# program, where both of them utilized function implemented in a VS compiled library.
For Matlab:
val = MyDLL.MyFunc(int32(a),int32(b),int32(c),int32(d));
Where:
MyDLL= actxserver('MyLib.MyClass');
As in C#, it's directly calling the function:
obj = new MyLib.MyClass;
val = obj.MyFunc(int32(a),int32(b),int32(c),int32(d));
However, in C# program, an exception from MyFunc would be raised but in MATLAB program nothing happens. Since they are essentially calling the same function from the same library, I reckon whether it could be the reason that MATLAB doesn't actually respond to exception raised from outer library?
Any advice would be helpful, thanks!
P.S.: All arguments match with each other and both programs are absolutely calling the very same function.

Related

Calling static method from m-file (octave/matlab)

I am currently having problems calling a static method located in an m-file, through the octave command interface. The error I'm getting is error: invalid call to script path/to/Test.m
Test.m:
classdef Test
methods(Static=true)
function ret = test_function()
ret = 0;
end
end
end
I am trying to call the method in the following way: > Test.test_function(). It's important to note that the script resides in the same directory in which I invoked the octave command, the script Test.m shows up using tab completion so the location is not at fault here I guess.
Any help is much appreciated,
thanks in advance!
From the Octave FAQ: "Matlab classdef object oriented programming is not yet supported, though work is underway in a branch of the development tree."
So the error is likely arising from the lack of classdef support, and the parser can't make sense of the call at all.

Can I view persisten variables in Matlab?

I have a problem that I'm having a hard time even framing for this question's title.
I have a library that calculates the properties of refrigerants. For example, you give pressure and enthalpy, and it tells you the temperature. That library is coded in Fortran with a mex file to interface with Matlab. Now, I am 100% sure that library is thoroughly debugged (it was coded by people much smarter than me, and has been used for almost a decade). The problem is definitely in how I call it.
And that problem is this. I call the library from a StartFcn callback (a .m script file) in a subsystem of a simulink model. The first time I run this model, it runs perfectly. The values I'm sedning to the function are therefore correct. The second time I run it, however, it crashes. The inputs both times are exactly the same.
Also, if I do a clear all between the two runs, then there is no crash. But if I do only clearvars or clear, I still get a crash. When I debug and look at the variables being passed in the function call, they are valid and the same both times.
Does someone have any experience with this, or can advise me on what I might be doing wrong? Is there something persisting within the function call that only clear all can remove and not clear? Save My Soul!
Yes, persistent variables can be declared by the persistent keyword.
If you want to clear only those, try
clear StartFcn
to clear all variables of the function StartFcn. A quote from the documentation:
If name is a function name, then clear name reinitializes any persistent variables in the function.
A quick thing to try would be clear mex inbetween simulations - this should clear all the mex code from matlab.
Other questions to think about..
Can you call the fortran interface directly from the matlab command line two times in a row?
I believe that using a m-file sfunction to call fortran in simulink is quite inefficient. Possibly consider writing your own fortran or C sfunction to interface to the code and compile in directly?
in case you're using LoadLibrary to load fortran code compiled into a dll, are you calling FreeLibrary in the mdlTerminate function?
Hope some of this helps.
I would try to put a clear all inside the function that you are calling in the StartFcn Callback.
So let's say your function is:
function [out] = nameoffunction(a,b,c)
%do calculation with a,b,c
d = a + b + c;
%output out
out = d;
assignin('base','out',d)
clear all
And you can call the function:
nameoffunction(a,b,c)
Let me know if it changes something. If this works, you could try other clear command but inside the function.

MATLAB Engine: engEvalString() won't return if given incomplete input

I'm using the MATLAB Engine C interface on OS X. I noticed that if engEvalString() is given an incomplete MATLAB input such as
engEvalString(ep, "x=[1 2");
or
engEvalString(ep, "for i=1:10");
then the function simply never returns. The quickest way to test this is using the engdemo.c example which will prompt for a piece of MATLAB code and evaluate it (i.e. you can type anything).
My application lets the user enter arbitrary MATLAB input and evaluate it, so I can't easily protect against incomplete input. Is there a workaround? Is there a way to prevent engEvalString() from hanging in this situation or is there a way to check an arbitrary piece of code for correctness/completeness before I actually pass it to MATLAB?
As you noted, it seems this bug is specific to Mac and/or Linux (I couldn't reproduce it on my Windows machine). As a workaround wrap the calls in eval, evalc, or evalin:
engEvalString(ep, "eval('x = [1,2')")
Furthermore, an undocumented feature of those functions is that they take a second input that is evaluated in case an error occurs in the first one. For example:
ERR_FLAG = false;
eval('x = [1,2', 'x=nan; ERR_FLAG=true;')
You can trap errors that way by querying the value of a global error flag, and still avoid the bug above...
This was confirmed by support to be a bug in the MATLAB Engine interface on OS X (it's not present in Windows). Workarounds are possible by using the MATLAB functions eval, evalc, or similar. Instead of directly passing the code to engEvalString(), wrap it in these first.

Cython callback causing memory corruption/segfaults

I am interfacing python with a c++ library using cython. I need a callback function that the c++ code can call. I also need to pass a reference to a specific python object to this function. This is all quite clear from the callback demo.
However I get various errors when the callback is called from c++ thread (pthread):
Pass function pointer and class/object (as void*) to c++
Store the pointers within c++
Start new thread (pthread) running a loop
Call function using the stored function pointer and pass back the class pointer (void*)
In python: cast void* back to class/object
Call a method of above class/object (Error)
Steps 2 and 3 are in c++.
The errors are mostly segmentation faults but sometimes I get complaints about some low level python calls.
I have the exact same code where I create a thread in python and call the callback directly. This works OK. So the callback itself is working.
I do need a separate thread running in c++ since this thread is communicating with hardware and on occasion calling my callback.
I have also triple-checked all the pointers that are being passed around. They point to valid locations.
I suspect there are some problems when using cython classes from a c++ thread..?
I am using Python 2.6.6 on Ubuntu.
So my question is:
Can I manipulate python objects from a non-python thread?
If not, is there a way can make the thread python-compatible? (pthread)
This is the minimal callback that already causes problems when called from c++ thread:
cdef int CheckCollision(float* Angles, void* user_data):
self = <CollisionDetector>user_data
return self.__sizeof__() # <====== Error
No, you must not manipulate Python objects without acquiring GIL in the first place. You must use PyGILState_Ensure() + PyGILState_Release() (see the PyGILState_Ensure documentation)
You can ensure that your object will be not deleted by python if you explicitly take the reference, and release it when you're not using it anymore with Py_INCREF() and Py_DECREF(). If you pass the callback to your c++, and if you don't have a reference taken anymore, maybe your python object is freed, and the crash happen (see the Py_INCREF documentatation).
Disclamer: i'm not saying this is your issue, just giving you tips to track down the bug :)

Call stack in compiled matlab

In matlab one can use dbstack to retrieve the call stack at the current time, however dbstack is not available in standalone compiled versions of matlab programs, is there an alternative to get the call stack, or at least the function calling the current function? I want to write a facility function that needs to know by who it was called, but a full call stack would be preferable.
Here's where the solutions stand so far:
As you mentioned, the function DBSTACK is on the list of functions that are not supported by the MATLAB Compiler, so it can't be used.
You also mentioned in a comment that even though the function EVALIN isn't on the unsupported function list your compiler still won't allow you to use it. That ended up rejecting some of the previous solutions I suggested.
Having to maintain your own stack trace by passing arguments along the chain of function calls (or possibly by storing them in a global variable) is not an ideal option due to the complexity and extra work it would take to maintain.
However, I have one more possible solution that I think is the "cleanest" one yet: using the error handling mechanisms to get at the stack trace. This will vary based on the MATLAB version you are using...
MATLAB Versions 7.5 (R2007b) and newer:
New error-handling capabilities in the form of the MException class were introduced in Version 7.5. You can get information about the stack trace from MException objects by creating and throwing a "dummy" exception, then immediately catching it and accessing the stack field. If you do the following in a function:
try
throw(MException('phony:error',''));
catch ME
callerStack = {ME.stack.name};
end
Then the cell array callerStack will contain the names of all the functions in the call stack, with the current function name in the first element and the top-most caller name in the last element.
MATLAB Versions 7.1 (R14SP3) through 7.4 (R2007a):
For these earlier versions you can use the ERROR function to throw an error and the LASTERROR function to capture the error and get the stack information:
try
error('phony:error','');
catch
s = lasterror;
callerStack = {s.stack.name};
end
MATLAB Versions 7.0.4 (R14SP2) and earlier:
Unfortunately, the LASTERROR function only started returning stack trace information in MATLAB Version 7.1, so there is no version of the above solutions that I can come up with for earlier MATLAB versions.