Integrate Code into Visual Studio using MATLAB Coder - c++

I created a dll file from Mathlab .m files using Matlab coder. In matlab, the matlab code runs fine without any error and DLL creation was successful. MV2010 compiles and runs fine. However, when the software calls any function from this DLL in Visual studio, i get "unhandled exception" with memory location and "access violation reading location" with another memory location.
I thought the created dll is depending on another dll that is missing. So, I used dependency Walker to check the dependency. However, dependency walker did not show any missing dependency.
The Matlab functions takes 5 input variables ( four as a double and one as 1D-array of double) and return 4 double values. So I thought it might be the size of the array i am passing to the matlab-generated code is small. So, I re-sized the array. The original size was 750, while new size is 5000. Still getting the same unhandled exception.
Any idea how to debug this unhandled exception? anything else i need to check for?
/* Function Declarations */
extern void mat3(double ValueF, double DesiredValue, double io, double del, emxArray_real_T *a, double *status, double *slope_deg, double *fval, double *SVal);
and I am calling this method in MS2010 as shown below.
double lValueF = 166.6;
double lDesiredValue = 42.00;
double io = 1.0;
double del = 4.0;
emxArray_real_T *lInputRoi;
// a = emxCreate_real_T(height,width);
lInputRoi = emxCreate_real_T(size_y,size_x);
// Converting 2D image to ID array
if(!isHorz)
{
int lRow = 0;
int lCol = 0;
for (int row=roi.y+odd_y_offset;row< roi.y+size_y;row=row+2)
{
lCol = 0;
for (int col=roi.x;col< roi.x+size_x;col++)
{
lInputRoi->data[lRow *size_x + lCol] = (real_T)img.at<uchar>(row,col);
lCol++;
}
lRow++;
}
}
else
{
int lRow = 0;
int lCol = 0;
for (int col=roi.x+odd_x_offset;col< roi.x+size_x;col=col+2)
{
lRow = 0;
for (int row=roi.y;row< roi.y+size_y;row++)
{
lInputRoi->data[lCol *size_y + lRow] = (real_T)img.at<uchar>(row,col);
lRow++;
}
lCol++;
size_x = roi.height;
size_y = roi.width;
}
}
// initializing matlab generated function
mat3_initialize();
double lStatus = 0;
double lslope_deg = 0.0;
double lfreqval = 0.0;
double lsfrvalue = 0.0;
mat3(lValueF, lDesiredValue, io, del, lInputRoi, &lStatus, &lslope_deg, &lfreqval, &lsfrvalue);
note:
1) img -> is the input image data.
2) roi -> is an object of struct type that has two int variables (x and y)
3) MV2010 application is an application that used "MFC in a shared DLL"
4) I have seen a tutorial on how to integrate the Mathlab generated dll in Microsoft Visual studio. However, the tutorial does not get any error. http://www.mathworks.com/videos/integrate-code-into-visual-studio-77402.html
Thanks you for any help in advance.

Related

Program crashes without error message

I am using the Qt Creator (Community) to learn how to code.
I have an assignment to calculate the roots of a function, and I tried using the code I found here in a Qt Widgets Project.
When I try to run the program, Qt didn't detect any errors.
However, my program crashes whenever I try to show the results using on_pushButton_clicked().
My lecturer suspects there should be an open loop somewhere but I don't see any.
Any help would be very much appreciated.
Code below:
double function1(double q)
{
double ab = ((q*q*q)+(9*q*q)-(15*q)+98)*(sin(q));
return ab;
}
void MainWindow::on_pushButton_clicked()
{
ui->label->setText(tr("%1").arg(func1()));
}
double MainWindow::func1()
{
std::setprecision(4);
double precision = 0.001;
double a = -10;
double b = -9;
double product = function1(a)*function1(b);
double absolute = fabs(a-b);
double e = 0;
if (product>0)
{
++a;
++b;
}
else
{
while (absolute >= precision)
{
e = (a + b) / 2;
double fa = function1(a);
double fe = function1(e);
if (fe == 0)
{
return e;
break;
}
if (fa*fe>0)
{
a = e;
}
else if (fa*fe<0)
{
b = e;
}
}
}
return e;
}
Try printing out the values of absolute and precision everytime this loop happens:
while (absolute >= precision)
.
That should help you figure it out.
If the program crashes when you click the button that "calls" on_pushButton_clicked, then it something wrong inside this slot.
Firstly, are all heap memory objects created previously with a new statement (in particular label)?
PS: you can remove the break instruction, function has already exited the while loop due to return in the line before.

terminate called after throwing an instance of std::bad_alloc

I am facing the current error since last few days and fighting with it to resolve the problem but all in vain. I am using Pythia8 and fastjet event generator together and running my simple code. Code compiled nicely but causes run time error as shown below. It runs fine with low events but for large iterations(events) it failed and print the error under discussion:
PYTHIA Warning in SpaceShower::pT2nextQCD: weight above unity
PYTHIA Error in StringFragmentation::fragment: stuck in joining
PYTHIA Error in Pythia::next: hadronLevel failed; try again
PYTHIA Error in SpaceShower::pT2nearQCDthreshold: stuck in loop
PYTHIA Error in StringFragmentation::fragmentToJunction: caught in junction flavour loop
PYTHIA Warning in StringFragmentation::fragmentToJunction: bad convergence junction rest frame
PYTHIA Warning in MultipleInteractions::pTnext: weight above unity
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
here is code:
[
double Rparam = 0.4;
fastjet::Strategy strategy = fastjet::Best;
fastjet::RecombinationScheme recombScheme = fastjet::Et_scheme;
fastjet::JetDefinition *jetDef = NULL;
jetDef = new fastjet::JetDefinition(fastjet::antikt_algorithm, Rparam,
recombScheme, strategy);
// Fastjet input
std::vector <fastjet::PseudoJet> fjInputs;
//================== event selection efficiency variables ==========
int nev=0;
int passedJetCut=0;
int passedBJetCut=0;
int passedLeptonCut=0;
int passedMtaunuCut=0;
int passedMtaunubCut=0;
int passedWCut=0;
int passedTopCut=0;
int passedMetCut=0;
int njets=2;
int nbjets=1;
int ntaus=1;
double MW=80.38;
// Begin event loop. Generate event. Skip if error. List first one.
for (int iEvent = 0; iEvent < HowManyEvents; ++iEvent) {
nev++;
if(iEvent%1000==0)cout<<"Event number "<<iEvent<<endl;
// cout<<"Event number "<<iEvent<<endl;
//==================== PYTHIA ==================
if(!pythia.next())continue;
// if (iEvent<3)pythia.process.list();
if (iEvent<2)pythia.event.list();
//if (iEvent<2)event.list();
//==================== TAUOLA ==================
// Convert event record to HepMC
HepMC::GenEvent * HepMCEvt = new HepMC::GenEvent();
//Conversion needed if HepMC uses different momentum units
//than Pythia. However, requires HepMC 2.04 or higher.
HepMCEvt->use_units(HepMC::Units::GEV,HepMC::Units::MM);
ToHepMC.fill_next_event(pythia, HepMCEvt);
// if (FirstEvent)event.list();
//Beware this does not reflect tauola effect
//tauola C++ interface only affects HepMC::GenEvent which is made
// from pythia.event
//run TAUOLA on the event
TauolaHepMCEvent * t_event = new TauolaHepMCEvent(HepMCEvt);
//Since we let Pythia decay taus, we have to undecay them first.
t_event->undecayTaus();
t_event->decayTaus();
// Reset Fastjet input for each event
fjInputs.resize(0);
// Keep track of missing ET
//*******************
class IsbFromTop {
public:
bool operator()( const HepMC::GenParticle* p ) {
if ( abs(p->pdg_id()) == 5 ) return 1;
return 0;
}
};
vector<bjet> bjets;
bjets.clear();
//======================= loop over particles ========================
for(HepMC::GenEvent::particle_const_iterator p = HepMCEvt->particles_begin();
p!= HepMCEvt->particles_end(); ++p ){
int pid=(*p)->pdg_id();
double pt=(*p)->momentum().perp();
double px=(*p)->momentum().px();
double py=(*p)->momentum().py();
double pz=(*p)->momentum().pz();
double e=(*p)->momentum().e();
double eta=(*p)->momentum().eta();
double phi=(*p)->momentum().phi();
if(abs(pid)==15){
if ( (*p)->production_vertex() ) {
for ( HepMC::GenVertex::particle_iterator mother =
(*p)->production_vertex()->particles_begin(HepMC::parents);
mother!=(*p)->production_vertex()->particles_end(HepMC::parents);
++mother )
{
if(abs((*mother)->pdg_id())==24){
W2Tau=true;
}
}
}
}
// Final state only
if ((*p)->status()!=1)continue;
if(abs(pid)==11 || abs(pid)==13){
if(!FoundLepton){
hleptonet->Fill(pt);
hleptoneta->Fill(eta);
hleptonphi->Fill(phi);
pxlepton=px;
pylepton=py;
pzlepton=pz;
elepton=e;
FoundLepton=true;
}
if(pt>20. && pt<80. && fabs(eta)<1.5)
nleptons++;
}
// No neutrinos
if (abs(pid)==12 ||
abs(pid)==14 ||
abs(pid)==16){nnu++;continue;}
// Only |eta| < 5
if(fabs(eta)>5.)continue;
// Missing ET
mex -= px;
mey -= py;
// Store as input to Fastjhttps://mail.google.com/mail/u/0/?shva=1#inboxet
fjInputs.push_back(fastjet::PseudoJet (px,py,pz,e));
}//loop over particles in the event
continue.............................
thanks a lot for your help
ijaz
Sorry I don't know anything about Pythia but in c++ new Operator will return either allocated memory pointer or it will throw a bad_alloc exception.
Using try catch we can solve this issue-
Like:
while(true)
{
try
{
string s = new string(1024*1024*1024);
break;
}
catch
{
// do stuff
}
}
It will solve the crashing issue but the CPU utilization will go UP until we got the required memory.(and if CPU reach at 100% usage it will hang the system)

How to return std::vector<std::vector<int>> from C++ to C++/CLI?

In my solution I have C++/CLI (vs2012) project that executes some method in C++ (vs2010) project.
Here is a signature of native code:
void Pcl::Downsample(std::vector<CloudPointNative>& points, std::vector<std::vector<int>>& clusters)
And here is how I execute it on C++/CLI side:
std::vector<std::vector<int>> clusters;
pcl->Downsample(points, clusters);
Then I try to iterate over clusters:
for (int clusterIndex = 0; clusterIndex < clusters.size(); clusterIndex++)
{
auto cluster = clusters[clusterIndex];
The size of clusters is 7 and each item in the vector contains vectors of int. I can see this in debugger on the native side. As soon as I get back to managed side (C++/cli project) I get problems.
It works correctly if clusterIndex == 0 and clusterIndex == 5. But throws AccessViolationException on any other values of clusterIndex.
auto cluster0 = clusters[0]; // works
auto cluster1 = clusters[1]; // AccessViolationException
auto cluster5 = clusters[5]; // works
How can this be?
Solved. I have changed signature to:
std::vector<std::vector<int>*>* Pcl::Downsample(std::vector<CloudPointNative>& points)
and also added Free method to delete the vectors
void Pcl::Free(std::vector<std::vector<int>*>* clusters)
{
for(int i = 0; i < clusters->size(); i++)
{
delete (*clusters)[i];
}
delete clusters;
}
Because objects created in external DLL should be also deleted in external DLL.

NLOpt with windows forms

I am suffering serious problems while trying to use nlopt library (http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial) in windows forms application. I have created following namespace which runs perfectly in console application.
#include "math.h"
#include "nlopt.h"
namespace test
{
typedef struct {
double a, b;
} my_constraint_data;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
my_constraint_data *d = (my_constraint_data *) data;
double a = d->a, b = d->b;
if (grad) {
grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
grad[1] = -1.0;
}
return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}
int comp()
{
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
my_constraint_data data[2] = { {2,0}, {-1,1} };
nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
nlopt_set_xtol_rel(opt, 1e-4);
double x[2] = { 1.234, 5.678 }; /* some initial guess */
double minf; /* the minimum objective value, upon return */
int a=nlopt_optimize(opt, x, &minf) ;
return 1;
}
}
It optimizes simple nonlinear constrained minimization problem. The problem arises when I try to use this namespace in windows form application. I am constantly getting unhandled exception in myfunc which sees "x" as empty pointer for some reason and therefore causes error when trying to access its location. I believe that the problem is somehow caused by the fact that windows forms uses CLR but I dont know if it is solvable or not. I am using visual studio 2008 and the test programs are simple console project (which works fine) and windows forms project (that causes aforementioned errors).
My test code is based on tutorial for C from the provided link. I although tried C++ version which once again works fine in console application but gives debug assertion failed error in windows forms application.
So I guess my questions is : I have working windows forms application and I would like to use NLOpt. Is there a way to make this work ?

How to coerce a xlTypeNum to double in C++ using Excel 2007 SDK

Well I am attempting to make my way through developing an Excel Add-in. I am trying small functions with the sample code in Excel 2007 SDK as as a guide. I am having difficulty with attempting to display a double type data in Excel. Assuming the UDF is called DisplayDouble() when the sample code is executed and a call is placed with an argument of real type data such as DisplayDouble(12.3) the sample code works yet if I attempt to use an argument that references a real type data from cell such as DisplayDouble(A1) where cell A1 in the Excel worksheet has the value 12.3 the sample code does not work
You can see the sample code below this paragraph. Any hints will help me move along the learning ladder
_declspec(dllexport) LPXLOPER12 WINAPI DisplayDouble (LPXLOPER12 n)
{
static XLOPER12 xResult;
XLOPER12 xlt;
int error = -1;
double d;
switch (n->xltype)
{
case xltypeNum:
d = (double)n->val.num;
if (max < 0)
error = xlerrValue;
xResult.xltype = xltypeNum;
xResult.val.num = d;
break;
case xltypeSRef:
error = Excel12f(xlCoerce, &xlt, 2, n, TempNum12(xltypeNum));
if (!error)
{
error = -1;
d = xlt.val.w;
xResult.xltype = xltypeNum;
xResult.val.num = d;
}
Excel12f(xlFree, 0, 1, &xlt);
break;
default:
error = xlerrValue;
break;
}
if ( error != - 1 )
{
xResult.xltype = xltypeErr;
xResult.val.err = error;
}
//Word of caution - returning static XLOPERs/XLOPER12s is not thread safe
//for UDFs declared as thread safe, use alternate memory allocation mechanisms
return(LPXLOPER12) &xResult;
}
looks like you coerced the value to xltypeNum but are then taking the integer value, with d = xlt.val.w rather than d = xlt.val.num