std::wstring in ChaiScript - wstring

I am a beginner for ChaiScript.
I try to use std::wstring type in ChaiScript.
std::string type is works well.
#include <iostream>
#include <chaiscript/chaiscript.hpp>
#include <chaiscript/chaiscript_stdlib.hpp>
int main()
{
chaiscript::ChaiScript chai(chaiscript::Std_Lib::library());
std::cout << chai.eval<std::function<int (std::string)> >(
"fun(s){"
" if(s==\"aaa\"){"
" print(\"1\");"
" }"
" if(s[1]=='b'){"
" print(\"2\");"
" }"
" return 3;"
"}"
)(std::string("abcd"));
}
D:\TestWork\test_chaiscript>t1.exe
2
3
std::wstring type raises an exception.
#include <iostream>
#include <chaiscript/chaiscript.hpp>
#include <chaiscript/chaiscript_stdlib.hpp>
int main()
{
chaiscript::ChaiScript chai(chaiscript::Std_Lib::library());
std::cout << chai.eval<std::function<int (std::wstring)> >(
"fun(s){"
" if(s==\"aaa\"){"
" print(\"1\");"
" }"
" if(s[1]=='b'){"
" print(\"2\");"
" }"
" return 3;"
"}"
)(std::wstring(L"abcd"));
}
D:\TestWork\test_chaiscript>t2.exe
terminate called after throwing an instance of 'chaiscript::exception::eval_error'
what(): Error: "Can not find appropriate '==' operator." With parameters: (NSt7__cxx1112basic_stringIwSt11char_traitsIwESaIwEEE, const string)
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
ChaiScript git version and mingw-w64 builds 5.1.0 are used.
g++ t2.cpp -std=c++14 -O2 -Os -Wall -mthreads -o t2.exe -DWIN32 -D_WIN32 -DUNICODE -D_UNICODE -Id:\myprj\chaiscript_git\include -static-libstdc++ -static-libgcc -Wl,-Bstatic -lstdc++ -lpthread -Wl,-Bdynamic
It is same in vs2013.
How can I use std::wstring type in ChaiScript?

std::wstring is just like any other type in ChaiScript - you have to tell ChaiScript how you want to use it.
In this case, you are trying to perform an == comparison, but have not provided ChaiScript with a operator==(const std::wstring &, const std::wstring &) function for it to use.
The easiest way to do this would be to use the existing code for std::string and expose all of the same functionality.
for example:
#include <chaiscript/dispatchkit/bootstrap_stl.hpp>
chai.add(chaiscript::bootstrap::standard_library::string_type<std::wstring>("wstring"));
For reference, see the bootstrap.hpp code that initializes std::string.

Related

Why do QProcess (Qt 5.15.1) and GDB lead to missing symbols?

I am currently having some trouble debugging a program that starts processes via QProcess.
Simply executing the binary without dbg works just fine but when I try to debug the executable with gdb I am getting a SIGTRAP when the process has started.
After that the stack always shows '??' instead of function names.
When continuing I get a SIGILL.
I found out that the trap is not caused when no breakpoint is set.
In my project I also get following output:
Probes-based dynamic linker interface failed.
I am not sure whether this is related to loaded plugins or libraries.
The problem can be reproduced (except from the " Probes-based dynamic linker interface failed." output) with the following code:
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QProcess proc;
QString exe = "echo";
QStringList arguments;
arguments << "Test";
proc.start(exe, arguments);
if (!proc.waitForFinished()) {
qDebug() << "failed to start" << proc.exitCode() << proc.errorString();
}
qDebug() << "process finished";
qDebug() << proc.readAllStandardOutput();
return a.exec();
}
My OS is arch linux (up to date)
Qt5: qt5-base 5.15.1-1
GDB: gdb 9.2-1
clang++: clang 10.0.1-1
Does anybody have an idea what is causing the SIGTRAP when debugging with dbg?

Cannot convert objects to pointers C++

I've stayed up all night trying to figure this out (it's now 7am where I'm at...).
I'm having trouble setting the address of an instantiated object to a pointer. Here's the main function:
#include "position_vector.h"
int main(){
PositionVector res = PositionVector(10);
PositionVector * ptr;
ptr = &res; // <--- WHERE IT BREAKS
}
A stripped down version of the h file "position_vector.h":
#include<iostream>
typedef uint32_t word_t;
class PositionVector {
public:
word_t * vec;
/*some other member variables */
PositionVector();
PositionVector(size_t len);
PositionVector & operator & ();
PositionVector & operator !();
~PositionVector();
/*some other member functions*/
void resize(size_t len);
};
I have another cpp file that defines all the methods in the class.
This is part of some larger set of code but here's the compile that fails:
g++-4.9 -std=c++11 -Werror -Wall -Wextra -g -Isrc -ggdb -c -o bin/main.o src/main.cpp
It fails with the error:
g++-4.9 -std=c++11 -Werror -Wall -Wextra -g -Isrc -ggdb -c -o bin/main.o src/main.cpp
src/main.cpp: In function ‘int main()’:
src/main.cpp:27:9: error: cannot convert ‘PositionVector’ to ‘PositionVector*’ in assignment
ptr = &res;
^
I must be missing something super basic but I've just pulled an all nighter and I have to run to work... so I cant really think full well any more.
You've overloaded operator& in your class:
class PositionVector {
// ...
PositionVector & operator & ();
};
When you than try to take the address, the compiler calls your overloaded member function which returns a PositionVector&. This cannot be assigned to a PositionVector* and thus you get the error.

Run gcc command from Qt Creator 5.4.0

I am trying to make a little IDE to compile c files. I am running under Ubuntu 14.04 and QtCreator 5.4.0. I wrote this code.
void MainWindow::on_pushButton_clicked()
{
QFile file("hello.c");
file.open(QIODevice::WriteOnly);
QTextStream out(&file);
out << ui->plainTextEdit->toPlainText();
QProcess::execute("gcc hello.c -o hello");
}
Everything is OK until run the gcc command. When I click on the button I get this error:
In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
and my C code is here:
#include <stdio.h>
int main () {
printf("Hello World..");
return 0;
}
You haven't flushed the QTextStream buffer, so hello.c is empty when you call gcc on it. Use QTextStream 's flush() to flush the buffer, it also calls flush on the underlying device (the QFile here).

qDebug not showing __FILE__,__LINE__

According to qlogging.h
#define qDebug QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug
but when I use like this, file,line,function name not show.
qDebug()<< "abc"; // only show abc;
qDebug()<< ""; // show nothing;
I search for a while, it seems no one had my problem like above.
I use ubuntu14.04,g++ version 4.8.2, qt5.3 build from git.
You can reformat from default output format.
This function was introduced in Qt 5.0.
The line number does not output because the default message pattern is "%{if-category}%{category}: %{endif}%{message}". This format means that the default outputting format is not including metadata like a line number or file name.
% cat logtest.pro
TEMPLATE = app
TARGET = logtest
mac:CONFIG-=app_bundle
SOURCES += main.cpp
% cat main.cpp
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
qSetMessagePattern("%{file}(%{line}): %{message}");
QCoreApplication a(argc, argv);
qDebug() << "my output";
return 0;
}
% qmake && make
% ./logtest
main.cpp(8): my output
You can also use QT_MESSAGE_PATTERN environment variable for setting the message pattern without calling qSetMessagePattern().
See reference for other placeholder. http://qt-project.org/doc/qt-5/qtglobal.html#qSetMessagePattern
If you dig in Qt history you can find out that the __FILE__ and __FUNCTION__ are logged only in debug builds since 1 Oct 2014. The git commit hash is d78fb442d750b33afe2e41f31588ec94cf4023ad. The commit message states:
Logging: Disable tracking of debug source info for release builds
Tracking the file, line, function means the information has to be
stored in the binaries, enlarging the size. It also might be a
surprise to some commercial customers that their internal file &
function names are 'leaked'. Therefore we enable it for debug builds
only.
Here's a simple example of how you might use the captured QMessageLogContext data in a custom message handler installed using qInstallMessageHandler. I didn't output the category or version members because they didn't seem useful. If desired you could also log to a file this way.
#include <QDebug>
#include <QString>
#include <QDateTime>
#include <iostream>
void verboseMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static const char* typeStr[] = {"[ Debug]", "[ Warning]", "[Critical]", "[ Fatal]" };
if(type <= QtFatalMsg)
{
QByteArray localMsg = msg.toLocal8Bit();
QString contextString(QStringLiteral("(%1, %2, %3)")
.arg(context.file)
.arg(context.function)
.arg(context.line));
QString timeStr(QDateTime::currentDateTime().toString("dd-MM-yy HH:mm:ss:zzz"));
std::cerr << timeStr.toLocal8Bit().constData() << " - "
<< typeStr[type] << " "
<< contextString.toLocal8Bit().constData() << " "
<< localMsg.constData() << std::endl;
if(type == QtFatalMsg)
{
abort();
}
}
}
int main()
{
//Use default handler
qDebug() << "default handler";
qWarning() << "default handler";
qCritical() << "default handler";
//Install verbose handler
qInstallMessageHandler(verboseMessageHandler);
qDebug() << "verbose handler";
qWarning() << "verbose handler";
qCritical() << "verbose handler";
//Restore default handler
qInstallMessageHandler(0);
qDebug() << "default handler";
qWarning() << "default handler";
qCritical() << "default handler";
return 0;
}
You can use standard C++'s __LINE__ and __FILE__. Also, take a look at What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__ SO question. If you use GCC, you can write __PRETTY_FUNCTION__ to get information about function from where the code executes. Just prepare debug-define you like.
For example, here is small compilable application:
#include <QApplication>
#include <QDebug>
#include <iostream>
// Qt-way
#define MyDBG (qDebug()<<__FILE__<<__LINE__<<__PRETTY_FUNCTION__)
// GCC
#define MyStdDBG (std::cout<< __FILE__<<":"<<__LINE__<<" in "<<__PRETTY_FUNCTION__<<std::endl)
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Qt-way
MyDBG;
MyDBG << "Something happened!";
// GCC
MyStdDBG;
return a.exec();
}
It gives next output:
../path/main.cpp 14 int main(int, char**)
../path/main.cpp 15 int main(int, char**) Something happened!
../path/main.cpp:18 in int main(int, char**)
UPD: Added pure C++-way to output.
I think you need to define:
#define qDebug() QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug()
and use it as
qDebug() << "abc";
or
#define qDebug QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug()
and use it as:
qDebug << "abc";
According to documentation qDebug() is already a macro to QMessageLogger(). Default Message handler prints only the message to stderr. I think you might want to use qInstallMessageHandler() to install your own message handler, that uses the context
Edit:
There is a relevant section in a manual, that describes this issue. In Qt4 context variable was not passed to installed message handler, so this solution is Qt5+ only. Default message handler does not make use of passed in context, but you can easily install your own, it's just a function pointer. There is even an example in the manual.
This depends on your Qt version number, whether you are using a debug build or a release build of Qt, and whether you have customized Qt message handling in your application.
According to Qt 5.4 documentation written in source code "qlogging.cpp":
QMessageLogger is used to generate messages for the Qt logging framework. Usually one uses
it through qDebug(), qWarning(), qCritical, or qFatal() functions,
which are actually macros: For example qDebug() expands to
QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO).debug()
for debug builds, and QMessageLogger(0, 0, 0).debug() for release builds.
So if you do not see file, line and function name information in your output, very likely you are using a release version of Qt.
If you still want to see the file, line and function name information in your output with a release version of Qt, there are several ways of achieving it, as very well explained in some of the previous answers.
If you wonder how to get the debug context in a non-debug build: Define QT_MESSAGELOGCONTEXT while compiling your code, and the information won't be stripped:
http://doc.qt.io/qt-5/qmessagelogcontext.html

Opencv2 cvtColor() does not work

I am using OpenCV2 on Ubuntu 12.04. I can successfully run image read-display codes.
However I am not able to run codes with inbuilt functions eg. cvtColor()
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdio.h>
int main(int argc, char *argv[])
{
cv::Mat image = cv::imread("img.jpg");
if( image.data == NULL )
{
printf( "file cannot be loaded\n");
return 1;
}
cv::namedWindow("My");
cv::imshow("My", image);
cv::Mat result;
cv::cvtColor(image, result, CV_BGR2Luv);
cv::imwrite("outImg.jpg", result);
cv::waitKey(0);
return 0;
}
I am using Qt-creator for my OpenCV
After compiling with --libs, --cflags I get following compiler error:
make: Entering directory `/home/swaroop/Work/ai-junkies/cuda/uc_davis/opencv2.x/OpenCV2Test'
g++ -g -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_WEBKIT -DQT_NO_DEBUG -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4 -I/usr/include/opencv -I. -o main.o main.cpp
main.cpp: In function 'int main(int, char**)':
main.cpp:22:29: error: 'CV_BGR2Luv' was not declared in this scope
main.cpp:22:39: error: 'cvtColor' was not declared in this scope
Please help me fix this.
cvtColor declared in opencv2/imgproc/imgproc.hpp
keep in mind it's #include not #import
#include <opencv2/imgproc/imgproc.hpp>
Alternatively, if you are testing things and not concerned with overdoing the includes, you can simply have one line:
#include <opencv2/opencv.hpp>
and it will include most opencv2 headers.

Resources