Controll of MATLAB dll from C++ code - c++

I run from C++ a MATLAB function (dll). This function gets some parameters and
runs a loop with many itterations. Is there is a way to set some flag in C++ code and check it on each itteration from MATLAB function. If this flag is set to false (let say by an other thread ) in C++ code MATLAB function will break the loop and return to C++ code

If you can modify both C++ and MATLAB codes (as we can assume from the question) I think the easiest way would be to use an empty file as the flag of an event. If some other thread can create a file, let's say 'event.flag', you can easily check its existence in MATLAB function:
if exist('event.flag','file')
% do_something
end
Make sure to include the second argument file, that will make exist run much faster.
I believe this solution is much easy and error-proof than trying to use any global variables.
If you need to exchange some data between MATLAB and other process in run time I'd recommend to use MEMMAPFILE object. Check the documentation to see if it will be appropriate in your case.

Related

Easiest way to add immediate task to a `CFRunLoop`?

What is the easiest way to add an immediate one-time task to a CFRunLoop from a C/C++ program, that is, a callback which must be invoked by the run-loop before it blocks again.
According to the documentation, we have CFRunLoopPerformBlock(), but the problem with it, is that it uses the block-notation which requires Objective-C compilation mode.
Is there something similar to CFRunLoopPerformBlock() which is available to a C/C++ program, or am I forced to use a zero-delay timer?
The block language feature does not require the use of Objective-C. It's also supported in C and C++ by Clang. So, you can go ahead and use CFRunLoopPerformBlock().
If you're still looking for alternatives and you wish to target the main thread's run loop (i.e. the main run loop), you can use dispatch_async_f(). Although it's most common to use the block-based functions when using GCD, the functions with the _f suffix take function pointers.
static void my_task_function(void *context)
{
// ...
}
...
dispatch_async_f(dispatch_get_main_queue(), any_pointer_you_like, my_task_function);

how to share a lib between process and called script subprocess using SWIG?

I have a C++ program foobar which starts with main() and then the flow of control goes through a first part, then the second part of the program. If I change main to foobar_main, I can then compile the whole program and a SWIG Python wrapper to a shared library foobar.so, and import this to Python, call foobar_main from within Python and everything works fine.
The second part communicates with the first one by some respectable C++ constructs. Specifically: the first part creates some single objects of some classes, and the second part uses class static methods to get those objects.
Now I want to run only the first part from main() and the second part from Python. That is, I want to start the C++ program foobar and then after the first part is finished, run a Python script (programmatically from within C++) that continues with the second part.
To do this, I:
compile the second part and a SWIG wrapper to foobar2.so
replace the second part of C++ code with system("python foobar2.py")
compile the modified C++ program to foobar1.so and load to foobar
write the script foobar2.py which imports foobar1 and foobar2 and then equivalent to the second part
Then I attempt to run foobar. It does not work, because it appears, that the routines in the second part complain that certain steps which should have been done in the first part, are not done.
This is embarasing but obviously I have some deep flaws here in my understanding of how computers work :) Can somebody clue me in what I am missing, including possibly simplifying the above process?
I'm going to assume your C++ code looks like this:
void part1()
{}
void part2()
{}
int main()
{
part1();
part2();
}
And that you have a Python version of part2() that is implemented with some other wrapped C++ functions. If these assumptions are wrong let me know.
I think the easiest way to go is to wrap part1() along with the other wrapped part2-related functions, then have a Python script like this:
import foobar
foobar.part1()
py_part2()
This of course means that the program starts in Python. If you need to start a C++ program for some reason (i.e. you need main()) then in order to use py_part2() you'll have to embed the Python interpreter inside your C++ program. This is a much more difficult and involved process, this answer has good info about how to get started.
Since you're learning I'll explain why system("python foobar2.py") doesn't work. In this scheme you have your C++ program start another process (program), named python, and then wait for it to finish. These are two completely different programs that in your case don't talk to each other and don't share anything in common. Hence why it doesn't work.
In general, reconsider anything that involves system. Its primary use seems to be to point out beginner programmers.

How to get the value of a variable that's deep in the source code (C++)? (eg. value of stage_sum in haar.cpp, OpenCV)

I'd like to get a value from a variable that's located deeply in the source code of the OpenCV library. Specifically, I'm trying to print out the value of stage_sum from the file haar.cpp. My starting point, facedetect.cpp, calls the method detectMultiScale, which then calls the function cvHaarDetectObjects, which calls cvHaarDetectObjectsForROC etc., until it finally reaches the function cvRunHaarClassifierCascadeSum, where stage_sum is calculated.
Is there a way I could get the value out to facedetect.cpp easily, without changing the declarations of all the preceding functions/methods, headers etc.? Simply trying to cout or printf the value directly in the source code hasn't given any results.
Thanks everyone for your help!
One option is simply to use a debugger.
However, if you want to do this programatically (i.e. access the variable as part of your application code), then unless the variable is exposed in the library's public interface, there are two options available:
Modify the library's source code, and recompile it.
Resort to undefined-behaviour (fiddling around with the raw bytes that make up an object, etc.).
Just to point the obvious, adding a std::cout() or printf() call inside haar.cpp won't do the trick. You need to recompile OpenCV for this changes to take effect and then reinstall the libraries on your system.

let the user use a function in c++ [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Dynamic source code in C++
is it possible to let the user type in a function and then run that function without using a lot of if's or a huge switch?
It is not possible to execute arbitrary c++ code in your program, since you than need a c++ compiler inside your program. But you could try to embed Python to your program. Boost python makes this relatively easy. The user can than write a python function that is executed and can interact with the classes and functions of your program. You need to make your functions explicitely visible to python.
What ever a user types in will be text, or a string. The only way I know to have it get mapped to a function is to use if/else or switch statements. That or the cringe inducing option of mapping each of your functions to a UI widget.
The end of the story, is it's your code. You have to write, and live with it. Just be careful, your program may be wildly successful, and you may not write code anymore, and then someone else will have to maintain your code. So be nice to the maintenance programmer who may follow you, and write code that isn't too tricky to figure out.
I assume you want something like eval from php.
You can try to play with command design pattern, but I doubt it will be an easy task. Basically you need to write simple C++ interpreter.
What type of function do you mean? A C++ function? If so, then you will have to either (1)interpret it or (2)compile and execute it. Interpretation would be the more likely choice here. I'm not sure if there are libraries out there already to do this but I'd assume there are.
If you don't like mega-if's or huge switches, you may be SoL on any solution for anything ever, but then again there is seldom one perfect way to do things. Consider looking in to various logic structures and algorithms to see how to do something that would normally be the job of a 23-case switch could be done another way. Like I said initially, however, sometimes you really do just need a million nested if's to do what you want to.
No, in C++ this is not possible. C++ is a compiled language. When the program runs, the compiler doesn't need to be accessible, or even installed on the machine that runs the program.
If you want to do this in C++, you need to write your own interpreter that parses whatever the user enters.
Here is my best idea, but it is a tad memory intensive.
First, create a class, lets call it MyFuncPtr to store a union of several different types of pointers to functions and an integer to tell which type it is. Overload the () operator to call the function stored with a variable length argument list. Make sure to include some sort of run-time argument checking.
Finally create a map of strings to MyFuncPtrs. Store your functions in this map along with their names. Then all you need to do is feed the name into the [] command to get a function that can be easily called. Templates could probably be used to aid in the making of MyFuncPtr instances.
This would be the easiest if it were plain C functions and no name mangling is performed on the symbols (use extern "C" { ... })
With some platform-specific code you can get the address of a function by its name. Then you cast the address as a function pointer which you can use to call the function.
On windows you must be using GetProcAddress and dlsym on Posix compliant platforms.

How do I abort a MATLAB m-file function from C/C++?

I deployed a MATLAB project into a DLL, to be called from C++, and it works just fine. Happy days.
But what happens when the user asks to cancel an operation?
I tried creating a global variable named UserAborted. I initialize it to 0 before running the long function in MATLAB. I also wrote the following two functions:
function AbortIfUserRequested
global UserAborted
if (UserAborted == 1)
error('User Abort');
end
end
function UserAbortLongFunction
global UserAborted
UserAborted = 1;
end
I call upon AbortIfUserRequested in every iteration of the loop in my long function. I also exported UserAbortLongFunction.
I expected that pretty soon after called UserAbortLongFunction, the long function would reach a call to AbortIfUserRequested, and throw an error.
Instead, the long function keeps running until the end, and only then does the value of UserAborted get changed.
All I want to do is abort that long function when the user asks me to! Is there any way to do that?
Try calling the DRAWNOW function in AbortIfUserRequested. Although Matlab is single-threaded (from an API perspective), it does allow for interrupts. I've had success by calling this function with pure M-code where user input (like Ctrl-C) otherwise gets locked out.
Matlab needs to provide callback functions to show execution progress and possibly halt it. A Google search shows lots of people wanting this but no implementation from Mathworks.
Matlab's single-threaded nature might be preventing the update to the global variable's value from propagating while the first function is executing. You could try sticking the abort flag in a Java object, like a HashMap, for a layer of indirection. Since Java objects are passed by reference, an update to its state may be visible immediately, without requiring a change to the Matlab variable itself.
Here's a snippet to do so. (Sorry, I don't have a Matlab Compiler license to test this out in a deployed DLL.)
function AbortIfUserRequested
global SharedState
if SharedState.get('UserAborted')
error('User Abort');
end
end
function UserAbortLongFunction
global SharedState
SharedState.put('UserAborted', 1);
end
function InitUserAbort
global SharedState
SharedState = java.util.Collections.synchronizedMap(java.util.HashMap());
SharedState.put('UserAborted', 0);
end
Matlab app data is also effectively passed by reference. Putting the abort flag in appdata instead of a global variable might work, too. If your library works with a Matlab GUI, you can put the app data on its figure handle instead of the global handle 0. This would be more idiomatic Matlab than the Java object, if it works.
function AbortIfUserRequested
if getappdata(0, 'UserAborted')
error('User Abort');
end
end
function UserAbortLongFunction
setappdata(0, 'UserAborted', 1);
end