using matlab dll file in Visual Studio C++ - c++

I created a dll file using "mcc" command in matlab from a simple add function like this:
function c = MyAdd(a,b)
c = a + b;
I entered this command:
mcc -t -L C -W lib:libMyAdd -T link:lib MyAdd.m libmmfile.mlib
it makes these files:
libMyAdd.lib
libMyAdd.c
libMyAdd.h
libMyAdd.dll
then i created an empty C++ project in VS and wrote this source code:
#include <iostream>
#include <conio.h>
#include "libMyAdd.h"
int main()
{
double k[4];
mwArray out;
out.GetData(k, 4);
// initialize MCR and lib
if (!mclInitializeApplication(NULL,0)) {
std::cerr << "could not initialize the application" << std::endl;
return -1;
}
if(!libMyAddInitialize()) {
std::cerr << "Could not initialize the library" << std::endl;
_getch();
return -1;
}
try {
// create input
double g[] = {1.0, 2.0, 3.0, 4.0};
double h[] = {5.0, 6.0, 7.0, 8.0};
mwArray in1(2, 2, mxDOUBLE_CLASS, mxREAL);
mwArray in2(2, 2, mxDOUBLE_CLASS, mxREAL);
in1.SetData(g, 4);
in2.SetData(h, 4);
// call function
mwArray out;
MyAdd(1, out, in1, in2);
// show result
std::cout << "in1 + in2 = " << std::endl;
std::cout << out << std::endl;
double k[4];
out.GetData(k, 4);
for(int i=0; i<4; i++) {
std::cout << k[i] << " " << std::endl;
}
} catch (const mwException& e) {
std::cerr << e.what() << std::endl;
return -2;
} catch (...) {
std::cerr << "Unexpected error thrown" << std::endl;
return -3;
}
// cleanup
libMyAddTerminate();
mclTerminateApplication();
return 0;
}
I also added this paths to my include and library directory in project properties->VC++ Directories as well as my additional library directories in linker->general
C:\Program Files\MATLAB\MATLAB Production Server\R2015a\extern\include
C:\Program Files\MATLAB\MATLAB Production Server\R2015a\extern\lib\win64\microsoft
Also, I added followings to Linker->Input->Additional Dependencies:
mclmcrrt.lib
libeng.lib
libmx.lib
libmex.lib
libmat.lib
mclmcr.lib
libMyAdd.lib
And since my matlab version is R2015a(64-bit), i changed the active solution platform to x64 (it was Win32).
the compiler shows no error, but a get a first-chance exception when I compile it (a picture of that uploaded).
what did i do wrong?
any suggestion?[a picture of that uploaded]
the error image

Related

Trying to compile example code from Octave's Standalone Programs example, getting segfault on first line

I am trying to learn how to embed Octave in my C++ code. When running the second example from here, the code compiles fine, but when running the code, a segmentation fault appears in the first line, when trying to initialize the interpreter. I'm not extremely adept at C++ but even when looking it up I can't find any answers.
The original code had octave::feval instead of feval, that threw a different, namespace error, so I just got rid of that and added the parse.h in the includes. I doubt this is at all related to the issue but that is a modification I did do.
#include <iostream>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/interpreter.h>
int
main (void)
{
// Create interpreter.
octave::interpreter interpreter;
try
{
int status = interpreter.execute ();
if (status != 0)
{
std::cerr << "creating embedded Octave interpreter failed!"
<< std::endl;
return status;
}
octave_idx_type n = 2;
octave_value_list in;
for (octave_idx_type i = 0; i < n; i++)
in(i) = octave_value (5 * (i + 2));
octave_value_list out = feval ("gcd", in, 1);
if (out.length () > 0)
std::cout << "GCD of ["
<< in(0).int_value ()
<< ", "
<< in(1).int_value ()
<< "] is " << out(0).int_value ()
<< std::endl;
else
std::cout << "invalid\n";
}
catch (const octave::exit_exception& ex)
{
std::cerr << "Octave interpreter exited with status = "
<< ex.exit_status () << std::endl;
}
catch (const octave::execution_exception&)
{
std::cerr << "error encountered in Octave evaluator!" << std::endl;
}
return 0;
}
The actual output is supposed to be:
GCD of [10, 15] is 5
I am using Linux Ubuntu 18.04 with Octave 4.2.2
The documentation looked at is a different version than the version I have installed on my computer. I have 4.2, but I was looking at 4.4 docs, which has different code for the task I was trying to accomplish.

C++ Access violation exception when calling Matlab compiled function: null pointer mistake?

I've searched extensively but there seems not to be a satisfying answer to this question online. So I'm posting again this problem in case someone has found a solution.
I have written a C++ code that is supposed to call some Matlab code. I have compiled all my Matlab files using the following command:
mcc -N -W cpplib:libRTR2 -T link:lib RTR.m -v
I have included the header, DLL and LIB files created by above command in the 'Header Files'for my Visual Studio project. I have also includde mclmcrrt.lib, mclmcrrt.h and mclcppclass.h in the same.
Here is my C++ code:
#define BZZ_COMPILER 3
#include <stdint.h>
#include "./hpp/BzzMath.hpp"
#include "libRTR2.h"
#include <iostream>
#include "mclmcrrt.h"
#include "mclcppclass.h"
double RTRtest(BzzVector &x)
{
x(1);
mwArray out(1,1);
try {
// create input
double a[] = { x[1] };
mwArray in1(1, 1, mxDOUBLE_CLASS, mxREAL);
in1.SetData(a, 1);
// call function
RTR(1, out, in1);
// show result
std::cout << "objFun" << std::endl;
std::cout << out << std::endl;
double F[1];
out.GetData(F, 1);
for (int i = 0; i<1; i++) {
std::cout << F[i] << " " << std::endl;
}
}
catch (const mwException& e) {
std::cerr << e.what() << std::endl;
return -2;
}
catch (...) {
std::cerr << "Unexpected error thrown" << std::endl;
return -3;
}
// cleanup
return out;
}
int optim()
{
if (!mclInitializeApplication(NULL, 0)) {
std::cerr << "could not initialize the application" << std::endl;
mclGetLastErrorMessage();
return -1;
}
if (!libRTR2Initialize()) {
std::cerr << "Could not initialize the library" << std::endl;
return -1;
}
bzzFilePrint("BzzRobustMinimization.txt");
BzzVector Xmin(1, 2000.);
BzzVector Xmax(1, 5000.);
BzzVector X0(1, 2000.);
double F0 = RTRtest(X0);
BzzMinimizationRobust m(X0, F0, RTRtest, Xmin, Xmax);
m();
m.BzzPrint("Results");
libRTR2Terminate();
mclTerminateApplication();
}
int main()
{
mclmcrInitialize();
return mclRunMain((mclMainFcnType)optim, 0, NULL);
}
And when I try to debug it I obtain this error:
Access Violation Error
I know it is related probably to trying to pass a null pointer to one of my functions, but being no expert in C++ I'm struggling to find where the error lies. Any help is greatly appreciated!

How to use caffemodel with OpenCV on iOS?

I am trying to use a .caffemodel alongside OpenCV on iOS devices. I found this github repository, but it can only be built with Xcode 6. I am working with Xcode 7, but I also downloaded Xcode 6 and still have no success on building it.
How can I use a caffemodel with OpenCV on iOS 9?
PS: The alternative would be this but it's written with swift & metal and I need to be able to use it with OpenCV.
You can use OpenCV DNN contrib module.
You need first to build OpenCV with contrib modules, you can find the steps here.
Then you can import and use the .caffemodel following this tutorial.
Here is an updated version of the tutorial, since it's not working as is:
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace cv::dnn;
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
/* Find best class for the blob (i. e. class with maximal probability) */
void getMaxClass(dnn::Blob &probBlob, int *classId, double *classProb)
{
Mat probMat = probBlob.matRefConst().reshape(1, 1); //reshape the blob to 1x1000 matrix
Point classNumber;
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.x;
}
std::vector<String> readClassNames(const char *filename = "synset_words.txt")
{
std::vector<String> classNames;
std::ifstream fp(filename);
if (!fp.is_open())
{
std::cerr << "File with classes labels not found: " << filename << std::endl;
exit(-1);
}
std::string name;
while (!fp.eof())
{
std::getline(fp, name);
if (name.length())
classNames.push_back( name.substr(name.find(' ')+1) );
}
fp.close();
return classNames;
}
int main(int argc, char **argv)
{
cv::dnn::initModule();
String modelTxt = "bvlc_googlenet.prototxt";
String modelBin = "bvlc_googlenet.caffemodel";
String imageFile = (argc > 1) ? argv[1] : "space_shuttle.jpg";
Ptr<dnn::Importer> importer;
try //Try to import Caffe GoogleNet model
{
importer = dnn::createCaffeImporter(modelTxt, modelBin);
}
catch (const cv::Exception &err) //Importer can throw errors, we will catch them
{
std::cerr << err.msg << std::endl;
}
if (!importer)
{
std::cerr << "Can't load network by using the following files: " << std::endl;
std::cerr << "prototxt: " << modelTxt << std::endl;
std::cerr << "caffemodel: " << modelBin << std::endl;
std::cerr << "bvlc_googlenet.caffemodel can be downloaded here:" << std::endl;
std::cerr << "http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel" << std::endl;
exit(-1);
}
dnn::Net net;
importer->populateNet(net);
importer.release(); //We don't need importer anymore
Mat img = imread(imageFile);
if (img.empty())
{
std::cerr << "Can't read image from the file: " << imageFile << std::endl;
exit(-1);
}
resize(img, img, Size(224, 224)); //GoogLeNet accepts only 224x224 RGB-images
dnn::Blob inputBlob = dnn::Blob(img); //Convert Mat to dnn::Blob batch of images
net.setBlob(".data", inputBlob); //set the network input
net.forward(); //compute output
dnn::Blob prob = net.getBlob("prob"); //gather output of "prob" layer
int classId;
double classProb;
getMaxClass(prob, &classId, &classProb);//find the best class
std::vector<String> classNames = readClassNames();
std::cout << "Best class: #" << classId << " '" << classNames.at(classId) << "'" << std::endl;
std::cout << "Probability: " << classProb * 100 << "%" << std::endl;
return 0;
} //main
I will post another answer because with recent versions there are some differences.
First of all now dnn is already inside the standard OpenCV library so you do not have to build it from contrib_modules.
The function to load the network is readNetFromCaffe.
For example the following code load the NN:
std::string modelName = "path/to/mymodel.caffemodel";
std::string protoName = "path/to/deploy.prototxt";
cv::dnn::Net net;
try
{
net = cv::dnn::readNetFromCaffe(protoName, modelName);
}
catch (cv::Exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
if (net.empty())
{
std::cerr << "Can't load network by using the following files: " << std::endl;
std::cerr << "prototxt: " << protoName << std::endl;
std::cerr << "caffemodel: " << modelName << std::endl;
std::cerr << "bvlc_googlenet.caffemodel can be downloaded here:" << std::endl;
std::cerr << "http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel" << std::endl;
exit(-1);
}
}
Then you can run the NN:
cv::Mat res_mat;
float res;
cv::Mat inputBlob = cv::dnn::blobFromImage(roi, 1.0f, cv::Size(227, 227),
cv::Scalar(0, 0, 0), false);
net.setInput(inputBlob);
//During the forward pass output of each network layer is computed,
//but in this example we need output from "prob" layer only.
res_mat = net.forward("score");
std::cout<<res_mat<<std::endl;
res_mat = res_mat.reshape(1, 1); //reshape the blob to 1x2 matrix
return res_mat.at<float>(0);
The function cv::dnn::blobFromImage resize the image to the input network size specified by the third argument (in my case cv::Size(227, 227)). The argument cv::Scalar(0, 0, 0) is to subtract the means from the three BGR channels.
score is the name of the output layer in the NN I used. You can see this information in the prototxt file.

C++: Error with Boost Filesystem copy_file

I'm running into some trouble with the copy_file function. My program is very simple, I'm just attempting to copy a text file from one spot to another.
The following code brings up a "Debug Error!" because abort() was called.
int main()
{
path src_path = "C:\\src.txt";
path dst_path = "C:\\dst.txt";
cout << "src exists = " << exists( src_path ) << endl; // Prints True
boost::filesystem::copy_file( src_path, dst_path );
return 0;
}
If I look at some other examples of code on Stackoverflow I cannot notice what I'm doing wrong. I feel like I'm missing something obvious here.
I have Boost v1.47 installed and I'm using Visual C++ 2010.
I'm guessing that the target file exists.
The docs:
template <class Path1, class Path2> void copy_file(const Path1& from_fp, const Path2& to_fp);
Requires: Path1::external_string_type and Path2::external_string_type are the same type.
Effects: The contents and attributes of the file from_fp resolves to are copied to the file to_fp resolves to.
Throws: basic_filesystem_error<Path> if from_fp.empty() || to_fp.empty() || !exists(from_fp) || !is_regular_file(from_fp) || exists(to_fp)
A simple test like so:
#include <iostream>
#include <boost/filesystem.hpp>
int main()
{
using namespace boost::filesystem;
path src_path = "test.in";
path dst_path = "test.out";
std::cout << "src exists = " << std::boolalpha << exists( src_path ) << std::endl; // Prints true
try
{
boost::filesystem::copy_file( src_path, dst_path );
} catch (const boost::filesystem::filesystem_error& e)
{
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
Prints:
src exists = true
Error: boost::filesystem::copy_file: File exists: "test.in", "test.out"
on the second run :)
I think if you are using boost::filesystem2 it should be
boost::filesystem2::copy(src_path,dest_path);
copy_file should have been deprecated.

log4cpp gives `unresolved external` errors

I'm trying to make work the library and run the tests provided with the latest version of log4cpp on Borland Codegear 2007, in which it's included a bpr project for Borland C++ Builder 5, which is meant to be able to build and run the different tests. The problem is that I'm trying to open this project with the 2007 version, which has to carry out a project conversion. I was getting weird 'unresolved external' errors. Then I've tried to build the project myself without converting anything, but got stuck in the same point.
I'm trying to run the following test :
#include <stdio.h>
#include "log4cpp/Portability.hh"
#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <iostream>
#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/OstreamAppender.hh"
#ifdef LOG4CPP_HAVE_SYSLOG
#include "log4cpp/SyslogAppender.hh"
#endif
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/NDC.hh"
int main(int argc, char** argv) {
log4cpp::Appender* appender;
#ifdef LOG4CPP_HAVE_SYSLOG
log4cpp::SyslogAppender* syslogAppender;
syslogAppender = new log4cpp::SyslogAppender("syslog", "log4cpp");
#else
log4cpp::Appender* syslogAppender;
syslogAppender = new log4cpp::OstreamAppender("syslogdummy", &std::cout);
#endif
if (argc < 2) {
appender = new log4cpp::OstreamAppender("default", &std::cout);
} else {
appender = new log4cpp::FileAppender("default", argv[1]);
}
syslogAppender->setLayout(new log4cpp::BasicLayout());
appender->setLayout(new log4cpp::BasicLayout());
log4cpp::Category& root = log4cpp::Category::getRoot();
root.addAppender(syslogAppender);
root.setPriority(log4cpp::Priority::ERROR);
log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1"));
sub1.addAppender(appender);
log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2"));
log4cpp::NDC::push(std::string("ndc1"));
std::cout << " root prio = " << root.getPriority() << std::endl;
std::cout << " sub1 prio = " << sub1.getPriority() << std::endl;
std::cout << " sub2 prio = " << sub2.getPriority() << std::endl;
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
sub2.error("sub2 error");
sub2.warn("sub2 warn");
sub1.setPriority(log4cpp::Priority::INFO);
std::cout << " root prio = " << root.getPriority() << std::endl;
std::cout << " sub1 prio = " << sub1.getPriority() << std::endl;
std::cout << " sub2 prio = " << sub2.getPriority() << std::endl;
std::cout << "priority info" << std::endl;
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
sub2.error("sub2 error");
sub2.warn("sub2 warn");
sub2.warnStream() << "streamed warn";
sub2 << log4cpp::Priority::WARN << "warn2" << " warn3"
<< log4cpp::eol << " warn4";
{
for(int i = 0; i < 10000; i++) {
char ndc2[20];
sprintf(ndc2, "i=%d", i);
log4cpp::NDC::push(ndc2);
sub1.info("%s%d", "i = ", i);
if ((i % 10) == 0) {
sub1.log(log4cpp::Priority::NOTICE, "reopen log");
if (log4cpp::Appender::reopenAll()) {
sub1.info("log reopened");
} else {
sub1.warn("could not reopen log");
}
}
#ifndef WIN32
sleep(1);
#endif
log4cpp::NDC::pop();
}
}
return 0;
}
The errors are all about 'unresolved external', such as:
[ILINK32 Error] Error: Unresolved external 'log4cpp::Category::warn(const char *, ...)' referenced from C:\DOCUMENTS AND SETTINGS\MLERMA\MIS DOCUMENTOS\RAD STUDIO\PROJECTS\DEBUG\TESTMAIN.OBJ
I'm getting this kind of error for every single call to a log4cpp function, all referring to TESTMAIN.OBJ .
Any ideas on this? is there anyone out there who has worked with log4cpp on Borland ?
Are you linking in the log4cpp library (.LIB)? I'm not familiar with BCB5 or Codegear but check your link libraries in your project settings and make sure the log4cpp library is included.
If it is, then you might have a problem with where the compiler is looking for libraries. Usually an IDE will have a project level or global setting that says where there compiler will look for .lib files. Check that setting and make sure one of those directories includes your log4cpp .lib file.
Mike
Try adding #pragma comment(lib,"ws2_32.lib") do your header file.