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.
Related
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.
Perl currently implements $SIG{__DIE__} in such a way that it will catch any error that occurs, even inside eval blocks. This has a really useful property that you can halt the code at the exact point where the error occurs, collect a stack trace of the actual error, wrap this up in an object, and then call die manually with this object as the parameter.
This abuse of $SIG{__DIE__} is deprecated. Officially, you are supposed to replace $SIG{__DIE__} with *CORE::GLOBAL::die. However, these two are NOT remotely equivalent. *CORE::GLOBAL::die is NOT called when a runtime error occurs! All it does is replace explicit calls to die().
I am not interested in replacing die.
I am specifically interested in catching runtime errors.
I need to ensure that any runtime error, in any function, at any depth, in any module, causes Perl to pass control to me so that I can collect the stack trace and rethrow. This needs to work inside an eval block -- one or more enclosing eval blocks may want to catch the exception, but the runtime error could be in a function without an enclosing eval, inside any module, from anywhere.
$SIG{__DIE__} supports this perfectly—and has served me faithfully for a couple of years or more—but the Powers that Be™ warn that this fantastic facility may be snatched away at any time, and I don't want a nasty surprise one day down the line.
Ideally, for Perl itself, they could create a new signal $SIG{__RTMERR__} for this purpose (switching signal is easy enough, for me anyway, as it's only hooked in one place). Unfortunately, my persuasive powers wouldn't lead an alcoholic to crack open a bottle, so assuming this will not happen, how exactly is one supposed to achieve this aim of catching runtime errors cleanly?
(For example, another answer here recommends Carp::Always, which … also hooks DIE!)
Just do it. I've done it. Probably everyone who's aware of this hook has done it.
It's Perl; it's still compatible going back decades. I interpret "deprecated" here to mean "please don't use this if you don't need it, ew, gross". But you do need it, and seem to understand the implications, so imo go for it. I seriously doubt an irreplaceable language feature is going away any time soon.
And release your work on CPAN so the next dev doesn't need to reinvent this yet again. :)
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.
I'm writing a matlab script where I'd like to know the name of the script which is one step up in the stack. The reason I need this is that I'm writing a helper script to be called to assert some basic facts about the workspace before engaging in heavier calculations, and the helper script should be able to give error messages when calling the calculation scripts.
I've tried using mfilename and dbstack, but I do not manage to get anything but the name of the helper script from them.
To explain further, I have the following scripts:
verify_base_conditions: the helper script, called on one of the first lines in
heavy_stuff_calculation and
sweet_mother_of_algorithms.
general_entry_point: a script where I gather common workflows in cells
I try to keep the entry point script as small as possible, and refactor heavier calculations (or anything that needs more than a few lines, really) into task-based, re-usable scripts. If I, from the entry point script, call sweet_mother_of_algorithms and the basic conditions for this script to run are not fulfilled, I want to see an error message like
Error: this_cool_var must be defined when running sweet_mother_of_algorithms
general_entry_point line 15
I tried using
error(['this_cool_var must be defined when running ' mdfilename])
and other similar constructs, but I couldn't make the error message say anything but verify_base_conditions.
How do I find the name of the script running one level up in the stack?
(Note: I'm not interested in finding the script running at the bottom of the stack - that will almost always be general_entry_point. I'm just interested in getting the name of the script that called verify_base_conditions.)
dbstack should work for this. I think this is an analogous set-up to yours:
a.m:
b;
b.m:
c;
c.m:
stack = dbstack;
for i=1:3
disp(stack(i));
end
When I run a;, this prints out the whole stack, including b (which I think it was you want - the second-top item on the call stack.
Alternatively, although this probably gives exactly the same result, you could throw and catch an error and look at its stack:
c.m:
try
error('What is on the call stack?');
catch e
for i=1:3
disp(e.stack(i));
end
end
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 :)