Call mex Function from cmex SFunction - c++

I have implemented a complex mexFunction using visual studio 2012 and successfully integrated it with Matlab. (lets call it mexFunctionA.mexw32 )
When I run this command in matlab command window, I get the expected results:
mexFunctionA("My1Argument", "My2Argument");
Now , I need to develop a mexFunctionB that calls mexFunctionA; mexFunctionB is a simple as it can be.
The C code I´m trying (inside mexFunctionB.c) is:
#include "mexFunctionA.mexw32"
(...)
static void mdlOutputs(SimStruct *S, int_T tid)
{
mexFunctionA("My1Argument", "My2Argument");
}
(...)
This line of code is not compiling.
The command line I am using is:
mex -v mexFunctionB.c -I'C:\patchToMexFunctionA' -L'C:\patchToMexFunctionA' 'mexFunctionA.mexw32'
So, here are the possible errors:
The #include method is wrong.
The command line for compiling the code is wrong.
It is not possible to do what I am planning to do.
Something else.
Anyone knows how to fix it?

The code you give is non-sensical. .mexw32 files are dynamically linked libraries (i.e. dll's), and in C code #include statements aren't used to include dll's.
Firstly note that as far as your S-Function is concerned mexFunctionA is no different from any other MATLAB function. So the question you should be asking is "how do I call a MATLAB function from within a mex file?".
The answer to that is to use the function mexCallMATLAB.
In short, you need to remove the #include and reformat the call to mexFunctionA to the form required by mexCallMATLAB.

Related

Call C++ Hello World from Julia

I have a C++ program that parses a binary file and outputs a std::string. I would like to call this function directly from Julia and convert the steam into a DataFrame. I need it to work in Linux and Windows. Currently, I have the program write the output to a text file, and then I read it into Julia. Cxx is no longer supported, and trying to get CxxWrap to work has been an exercise in frustration.
Toy Problem:
If someone could show me how to call the code below from Julia, that would be awesome.
// the example from https://github.com/JuliaInterop/CxxWrap.jl
#include <string>
std::string greet()
{
return "hello, world";
}
There's a new package which might fit your needs here:
https://github.com/eschnett/CxxInterface.jl
It is intended as a successor to Cxx.jl and more stable, so I'd recommend giving it ago although I haven't tried it myself!

Plot values in .m file from C++

I have looked extensively in the net, yet not found exactly what I want.
I have a big simulation program that outputs results in a MATLAB M-file (let's call it res.m) and I want to plot the results visually.
I want to start the simulation with C++ many times in a row and therefore want to automatize the plotting of the results.
I come up to two options:
Execute from C++ an Octave or MATLAB script that generates the graph.
-> Haven't found anyone who managed to do so
Use the Octave source files to read the res.m file and output them after with whatever plotting C++ tool.
-> Theoretically possible but I get lost in those files
Is someone able to solve this? Or has a better, easier approach?
The answer is to execute through the terminal.
I didn't manage to actually run a octave script from my c++ program directly, but there is a way around messing with/through the terminal and a extra Octave file. I used in my cpp:
string = "octave myProgr.m"
const char *command = str.c_str();
system(command);
myProgr.m is the script that plots the res.m file

Matlab system() running C++ Executable

I'm having some trouble getting Matlab to run an executable file. Essentially, I have a C++ code that does some calculations and outputs these calculations to a text file; then, Matlab reads these text files and uses the calculations to makes plots and stuff.
I've been trying to get Matlab to run the C++ exe file so that, when it runs it, the output files are automatically generated and Matlab can start doing its stuff. This just allows the user to run the program quicker. I am using the system() command Like so:
system('MyCppProgram.exe');
However, when I run that, although everything compiles, nothing is outputted from CPP and I even get back something that says "ans = -1" and I have no idea what that means.
Any help would be greatly appreciated. Thank you!
Update: Result from test command.
[status, cmdout] = system('MyCppProgram.exe', '-echo');
status = -1
cmdout = ''

"??? Undefined function or method" in Matlab Engine command window

I am working with Visual Studio on C++ code, and I send some variables to MATLAB engine. So far there is no problem. Imagine I have the MATLAB command window opened and these variables:
» whos
Name Size Bytes Class Attributes
QWe 1x365 2920 double
QWp 1x364 2912 double
QWu 1x364 2912 double
I can use the standard MATLAB functions, but I have dowloaded a new function.m (which works in MATLAB normally after setting the path) that this command window from MATLAB's engine is not recognizing or finding.
» isnormq(Q)
??? Undefined function or method 'isnormq'
I thought they (command window and MATLAB) were synchronized but now I see they aren't.
How can I solve this so I can use my function.m from the command window? Any help will be welcomed.
As it has been a long time and nobody answered I will post what I did:
In Matlab everytime you need a newtoolbox you link the path once and there stays "forever". You can use functions from the toolbox as if they were by default in Matlab.
Using matlab engine this doesn't work that way so it is necessary to write the command line:
% Here we load the toolbox for converting quaternion to Euler Angles
addpath(genpath('C:\Program Files (x86)\MATLAB\R2010a\toolbox\SpinCalc')); //for example
It's been a long time but I face the same problem and find some interesting information about it.
First of all at the newer version of MATLAB (2016a) MATLAB Engine search path is C:\Program Files\MATLAB\R2016a (Or the same path where you install MATLAB). So if you don't change it C++ can use all the build-in functions. Furthermore, you can using functions from Toolboxes!
But there is another one problem: what about user defined functions? So I need to put .m file directly to C:\Program Files\MATLAB\R2016a to make it visible for MATLAB Engine.
Here we can go another way - just add the path of your .m file to MATLAB through C++:
char CommandChangePath[MAX_PATH];
strcpy(CommandChangePath, "addpath('C:\\Users\\SuperUser\\Documents\\Visual Studio 2017\\Projects\\MyCppProject')");
engEvalString(ep, CommandChangePath);
For me its very useful to put necessary MATLAB function in current C++ project, add the path and use then! Now you don't need to change the path at every step - it's remembered and useful always for current application.

LoadLibrary fails when including a specific file during DLL build

I'm getting really strange behavior in one of the DLLs of my C++ app. It works and loads fine until I include a single file using #include in the main file of the DLL. I then get this error message:
Loading components from D:/Targets/bin/MatrixWorkset.dll
Could not load "D:/Targets/bin/MatrixWorkset.dll": Cannot load library MatrixWorkset: Invalid access to memory location.
Now I've searched and searched through the code and google and I can't figure out what is going on. Up till now everything was in a single DLL and I've decided to split it into two smaller ones. The file that causes the problems is part of the other second library (which loads fine).
Any ideas would really be appreciated.
Thanks,
Jaco
The likely cause is a global with class type. The constructor is run from DllMain(), and DllMain() in turn runs before LoadLibrary() returns. There are quite a few restrictions on what you can do until DllMain() has returned.
Is it possible that header includes a #pragma comment(lib,"somelibrary.lib") statement somewhere? If so it's automatically trying to import a library.
To troubleshoot this I'd start by looking at the binary with depends (http://www.dependencywalker.com/), to see if there are any DLL dependencies you don't expect. If you do find something and you are in Visual Studio, you should turn on "Show Progress" AKA /VERBOSE on the linker.
Since you are getting the Invalid Access to memory location, it's possible there's something in the DLLMAIN or some static initializer that is crashing. Can you simplify the MatrixWorkset.dll (assuming you wrote it)?
The error you describe sounds like a run-time error. Is this error displayed automatically by windows or is it one that your program emits?
I say attach a debugger to your application and trace where this error is coming from. Is Windows failing to load a dependency? Is your library somehow failing on load-up?
If you want to rule in/out this header file you're including, try pre-compiling your main source file both with and without this #include and diff the two results.
I'm still not getting it going. Let me answer some of the questions asked:
1) Windows is not failing to load a dependency, I think since Dependency Walker shows everything is ok.
2) I've attached a debugger which basically prints the following when it tries to load MatrixWorkset.dll:
10:04:19.234
stdout:&"warning: Loading components from D:/ScinericSoftware/VisualWorkspace/trunk/Targets/bin/MatrixWorkset.dll\n"
10:04:19.234
stdout:&"\n"
status:Stopped: "signal-received"
status:Stopped.
10:04:19.890
stdout:30*stopped,reason="signal-received",signal-name="SIGSEGV",signal-meaning="Segmentation fault",thread-id="1",frame={addr="0x7c919994",func="towlower",args=[],from="C:\\WINDOWS\\system32\\ntdll.dll"}
input:31info shared
input:32-stack-list-arguments 2 0 0
input:33-stack-list-locals 2
input:34-stack-list-frames
input:35-thread-list-ids
input:36-data-list-register-values x
10:04:19.890
3) MSalters: I'm not sure what you mean with a "global with class type". The file that is giving the problems have been included in a different DLL in which it worked fine and the DLL loaded successfully.
This is the top of the MatrixVariable.h file:
#include "QtSF/Variable.h" // Located in depending DLL (the DLL in which this file always lived.
#include "Matrix.h" // File located in this DLL
#include "QList" // These are all files from the Qt Framework
#include "QModelIndex"
#include "QItemSelection"
#include "QObject"
using namespace Zenautics;
using namespace std;
class MatrixVariable : public Variable
{
Q_OBJECT
Q_PROPERTY(int RowCount READ rowCount WRITE setRowCount)
Q_PROPERTY(int ColumnCount READ columnCount WRITE setColumnCount)
Q_PROPERTY(int UndoPoints READ undoPoints WRITE setUndoPoints)
public:
//! Default constructor.
MatrixVariable(const QString& name, int rows, int cols, double fill_real = 0, double fill_complex = 0, bool isReal = true);
etc. etc. etc.
A possible solution is to put the MatrixVariable file back in the original DLL but that defeats the whole idea of splitting the DLL into smaller parts which is not really a option.
I get that error from GetLastError() when I fail to load a DLL from a command line EXE recently. It used to work, then I added some MFC code to the DLL. Now all bets are off.
I just had this exact same problem. A dll that had been working just fine, suddenly stopped working. I was taking an access violation in the CRT stuff that initializes static objects. Doing a rebuild all did not fix the problem. But when I manually commented out all the statics, the linker complained about a corrupt file. Link again: Worked. Now I can LoadLibrary. Then, one by one, I added the statics back in. Each time, I recompiled and tested a LoadLibrary. Each time it worked fine. Eventually, all my statics were back, and things working normally.
If I had to guess, some intermediate file used by the linker was corrupted (I see the ilk files constantly getting corrupted by link.exe). If you can, maybe wipe out all your files and do a clean build? But I'm guessing you've already figured things out since this is 6 months old ...