Command line parser for Qt4 - command-line

I am looking for a command line parser for Qt4.
I did a small google search, and found this: http://www.froglogic.com/pg?id=PublicationsFreeware&category=getopt however it lacks support for "--enable-foo" and "--disable-foo" switches. Besides that, it looks like a real winner.
EDIT:
It seems Frologic removed this. So the best options I see are using Boost (which is not API nor ABI stable) or forking the support for kdelibs. Yay...

QCoreApplication's constructors require (int &argc, char **argv) (and QApplication inherits from QCoreApplication). As the documentation states, it is highly recommended that
Since QApplication also deals with common command line arguments, it is usually a good idea to create it before any interpretation or modification of argv is done in the application itself.
And if you're letting Qt get the first pass at handling arguments anyways, it would also be a good idea to use QStringList QCoreApplication::arguments() instead of walking through argv; QApplication may remove some of the arguments that it has taken for its own use.
This doesn't lend itself to being very compatible with other argument-parsing libraries...
However, kdelibs does come with a nice argument parser, KCmdLineArgs. It is LGPL and can be used without KApplication if you really want (call KCmdLineArgs::init).
KCmdLineOptions options;
options.add("enable-foo", ki18n("enables foo"));
options.add("nodisable-foo", ki18n("disables foo"));
// double negatives are confusing, but this makes disable-foo enabled by default
KCmdLineArgs::addCmdLineOptions(options);
KApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if (args->isSet("enable-foo") && !args->isSet("disable-foo"))
cout << "foo enabled" << endl;
else
cout << "foo disabled" << endl;
Untested (who ever tests what they post on S.O.?).

Since Qt 5.2 you can finally find a solution in QtCore itself: I contributed QCommandLineParser there.

This is more or less the same answer as ephemient, but with a simple regexp to help parse the args. (This way could be useful if you only need a handful of args)
Run with this:
./QArgTest --pid=45 --enable-foo
And the code:
int main(int argc, char *argv[]) {
QApplication app(argc, argv, false);
qDebug() << "QApp arg test app";
QStringList args = app.arguments();
int pid = 0;
QRegExp rxArgPid("--pid=([0-9]{1,})");
QRegExp rxArgFooEna("--enable-foo");
QRegExp rxArgFooDis("--disable-foo");
for (int i = 1; i < args.size(); ++i) {
if (rxArgPid.indexIn(args.at(i)) != -1 ) {
pid = rxArgPid.cap(1).toInt();
qDebug() << i << ":" << args.at(i) << rxArgPid.cap(1) << pid;
}
else if (rxArgFooEna.indexIn(args.at(i)) != -1 ) {
qDebug() << i << ":" << args.at(i) << "Enable Foo";
}
else if (rxArgFooDis.indexIn(args.at(i)) != -1 ) {
qDebug() << i << ":" << args.at(i) << "Disable Foo";
}
else {
qDebug() << "Uknown arg:" << args.at(i);
}
}
return 0;
}

There is also QxtCommandOptions from http://www.libqxt.org/

That package does support --disable-foo and --enable-foo via opts.addSwitch("disable-foo", &foo_disabled); and opts.addSwitch("enable-foo", &foo_enabled);. You need handle checking both, and dealing with someone specifying both (oops).
What I don't understand is how this has anything to do with QT4...

Look at this: http://code.google.com/p/qtargparser/

A really simple method is to scan "key=value" args,
put them in a table say zz.map: QString -> QVariant,
and get their values with zz.map.value( key, default ).
An example:
#include "ztest.h"
Ztest zz;
int main( int argc, char* argv[] )
{
zz.eqargs( ++ argv ); // scan test=2 x=str ... to zz.map
QString xx = zz.map.value( "xx", "" );
if( Zint( Size, 10 )) // a #def -> zz.map.value( "Size", 10 )
...
ztest.h is < 1 page, below; same for Python ~ 10 lines.
(Everybody has his/her favorite options parser;
this one's about the simplest.
Worth repeating: however you specify options, echo them to output files --
"every scientist I know has trouble keeping track
of what parameters they used last time they ran a script".)
To make QPoints etc work one of course needs a QString -> QPoint parser.
Anyone know offhand why this doesn't work (in Qt 4.4.3) ?
QPoint pt(0,0);
QDataStream s( "QPoint(1,2)" );
s >> pt;
qDebug() << "pt:" << pt; // QPoint(1364225897,1853106225) ??
Added 25nov --
// ztest.h: scan args x=2 s=str ... to a key -> string table
// usage:
// Ztest ztest;
// int main( int argc, char* argv[] )
// {
// QApplication app( argc, argv );
// ztest.eqargs( ++ argv ); // scan leading args name=value ...
// int x = Zint( x, 10 ); // arg x= or default 10
// qreal ff = Zreal( ff, 3.14 );
// QString s = Zstr( s, "default" );
// care: int misspelled = Zint( misspellled ) -- you lose
//version: 2009-06-09 jun denis
#ifndef ztest_h
#define ztest_h
#include <QHash>
#include <QString>
#include <QVariant>
#include <QRegExp>
//------------------------------------------------------------------------------
class Ztest {
public:
QHash< QString, QVariant > map;
int test; // arg test=num, if( ztest.test )
Ztest() : test( 0 ) {}
QVariant val( const QString& key, const QVariant& default_ = 0 )
{
return map.value( key, default_ );
}
void setval( const QString& key, const QVariant& val )
{
map[key] = val;
if( key == "test" || key == "Test" )
test = val.toInt();
}
//------------------------------------------------------------------------------
// ztest.eqargs( ++ argv ) scans test=2 x=3 ... -> ztest table
void eqargs( char** argv )
{
char** argv0 = argv;
char *arg;
QRegExp re( "(\\w+)=(.*)" ); // name= anything, but not ./file=name
for( ; (arg = *argv) && re.exactMatch( arg ); argv ++ ){
setval( re.cap(1), re.cap(2) );
}
// change argv[0..] -> args after all name=values
while(( *argv0++ = *argv++) != 0 ) {}
}
};
extern Ztest ztest;
// macros: int x = Zint( x, 10 ): x= arg or default 10
#define Zstr( key, default ) ztest.val( #key, default ).toString()
#define Zint( key, default ) ztest.val( #key, default ).toInt()
#define Zreal( key, default ) ztest.val( #key, default ).toDouble()
#endif

It's 2013 and still no "1st party" arg parser. Anyways..if anyone finds themselves facing the same problem and would like to avoid the learning curves that come with cmd parser libs, here is a "quick & dirty" fix for you:-
QString QArgByKey(QString key, QChar sep = QChar('\0') ) //prototype usually in separate header
QString QArgByKey(QString key, QChar sep )
{
bool sepd=sep!=QChar('\0');
int pos=sepd?qApp->arguments().indexOf(QRegExp('^'+key+sep+"\\S*")):qApp->arguments().indexOf(QRegExp(key));
return pos==-1?QString::null:
(sepd?qApp->arguments().at(pos).split(sep).at(1):(++pos<qApp->arguments().size()?qApp->arguments().at(pos):QString::null));
}
Example:-
user#box:~$ ./myApp firstKey=Value1 --secondKey Value2 thirdKey=val3.1,val3.2,val3.3 --enable-foo
Usage:
QString param1 = QArgByKey("firstkey",'='); // Returns `Value1` from first pair
QString param2 = QArgByKey("--secondkey"); // Returns `Value2` from second pair
QString param3-1 = QArgByKey("thirdkey",'=').split(',').at(0); // Returns `val3.1`
bool fooEnabled = qApp->arguments().contains("--enable-foo"); //To check for `--enable-foo`
Params can be passed in any order
Edit: Updates to this snippet will be found here

Does it have to be Qt4 specific? If not, GNU Getopt is really nice, although licensing may be a problem if you are not doing open source software.

Also for some fancy options parsing you can try gperf.
IBM has a nice tutorial on it.

Another option I ran across while looking to do this, too:
http://code.google.com/p/qgetopts/
I haven't used it though.

Related

What does it mean when CreateNamedPipe returns of 0xFFFFFFFF perror() says "NO ERROR'?

I am using CreateNamedPipe. It returns 0XFFFFFFFF but when I call GetLastError and perror I get "NO ERROR".
I have checked https://learn.microsoft.com/en-us/windows/win32/ipc/multithreaded-pipe-server and I heve coded very similar.
I coded this using an example provided here: https://stackoverflow.com/questions/47731784/c-createnamedpipe-error-path-not-found-3#= and he says it means ERROR_PATH_NOT_FOUND (3). But my address is "\\.\pipe\pipe_com1. Note that StackOverflow seems to remove the extra slashes but you will see them in the paste of my code.
I followed the example here: Create Named Pipe C++ Windows but I still get the error. Here is my code:
// Create a named pipe
// It is used to test TcpToNamedPipe to be sore it it is addressing the named pipe
#include <windows.h>
#include <stdio.h>
#include <process.h>
char ch;
int main(int nargs, char** argv)
{
if (nargs != 2)
{
printf("Usage pipe name is first arg\n");
printf("press any key to exit ");
scanf("%c", &ch);
return -1;
}
char buffer[1024];
HANDLE hPipe;
DWORD dwRead;
sprintf(buffer, "\\\\.\\pipe\\%s", argv[1]);
hPipe = CreateNamedPipe((LPCWSTR)buffer,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
1,
1024*16,
1024*16,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
//int errorno = GetLastError();
//printf("error creating pipe %d\n", errorno);
perror("");
printf("press any key to exit ");
scanf("%c", &ch);
return -1;
}
while (hPipe != INVALID_HANDLE_VALUE)
{
if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe
{
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
{
/* add terminating zero */
buffer[dwRead] = '\0';
/* do something with data in buffer */
printf("%s", buffer);
}
}
DisconnectNamedPipe(hPipe);
}
return 0;
}
I'm guessing that the pointer to the address may be wrong and CreateNamedPipe is not seeing the name of the pipe properly. So I used disassembly and notice that the address is in fact a far pointer. Here is that disassembly:
00CA1A45 mov esi,esp
00CA1A47 push 0
00CA1A49 push 0
00CA1A4B push 4000h
00CA1A50 push 4000h
00CA1A55 push 1
00CA1A57 push 0
00CA1A59 push 3
00CA1A5B lea eax,[buffer]
00CA1A61 push eax
00CA1A62 call dword ptr [__imp__CreateNamedPipeW#32 (0CAB00Ch)]
Can someone spot my problem?

Access to OS functions from CAPL

I'm doing a script using CAPL and am stuck for a solution to grep the login ID from Windows. Could some please help show how to get Windows user login ID from within a CAPL program code, if this is possible?
For example, if the Windows user login ID is 'kp21ml' , I want to read this ID from a CAPL function, as shown below.
byte UserIdCheck()
{
char uid[10];
byte CanMessageTrasmission;
strncpy(uid, xxxx(), 6); // where xxxx() is the unknown OS or system function that could return the login ID ?
if (strncmp(uid, "kp21ml") != 0)
{
write("Access denied!"); // Message to CANoe's Write window
CanMessageTrasmission = 0;
}
else
{
// Access ok
CanMessageTrasmission = 1;
}
return CanMessageTrasmission;
}
I use this CAPL book as my reference guide, which is very good:
http://docplayer.net/15013371-Programming-with-capl.html
But I couldn't find anything to do with system access. I would appreciate your help.
Thanks
Juno
I'm afraid you won't be able to do that directly from a CAPL script.
I generally create a CAPL-DLL and include that in my CANoe project when I need to access some OS level functionality. Though I use it mostly for accessing an external device (e.g. USB) or to interact with another program using sockets over local host, the principle is the same.
You can find more information in CANoe's documentation with examples but the CAPL-DLL source code provided in CANoe samples is a little difficult to understand.
I've attempted to strip some of the "unnecessary" parts in the following code sample; this example will create a CAPL-DLL which "exposes" the multiplyBy10 function and basically allows you to call multiplyBy10 from you CAPL script):
#define USECDLL_FEATURE
#define _BUILDNODELAYERDLL
#pragma warning( disable : 4786 )
#include "cdll.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <map>
char moduleName[_MAX_FNAME];
HINSTANCE moduleHandle;
unsigned int
CAPLEXPORT far CAPLPASCAL multiplyBy10 (unsigned char value)
{
unsigned int result = value * 10;
freopen("CONOUT$", "w", stdout);
std::cout << "multiplyBy10() - value: " << int(value) << ", result: " << result << std::endl;
return (result);
}
CAPL_DLL_INFO4 table[] =
{
{CDLL_VERSION_NAME, (CAPL_FARCALL)CDLL_VERSION, "", "", CAPL_DLL_CDECL, 0xABD, CDLL_EXPORT},
{"multiplyBy10", (CAPL_FARCALL)multiplyBy10, "CAPL_DLL", "This is a demo function", 'L', 1, "D", "", { "value"}},
{0, 0}
};
CAPLEXPORT CAPL_DLL_INFO4 far * caplDllTable4 = table;
bool
WINAPI DllMain(HINSTANCE handle, DWORD reason, void*)
{
static FILE * stream;
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
moduleHandle = handle;
char path_buffer[_MAX_PATH];
DWORD result = GetModuleFileName(moduleHandle, path_buffer, _MAX_PATH);
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_splitpath_s(path_buffer, drive, dir, fname, ext);
strcpy_s(moduleName, fname);
AllocConsole();
freopen_s(&stream, "conout$", "w", stdout);
std::cout << "DLL_PROCESS_ATTACH" << std::endl;
return 1;
}
case DLL_PROCESS_DETACH:
{
std::cout << "DLL_PROCESS_DETACH" << std::endl;
FreeConsole();
fclose(stream);
return 1;
}
}
return 1;
}

How to use a widget plugin in qt 3?

For some reasons, I must work with Qt3 under SLES 11 SP3. I have written the following plugin:
// PixmapButtonPlugin.hpp
#include <qwidgetplugin.h>
class PixmapButtonPlugin : public QWidgetPlugin
{
public:
QStringList keys () const;
QWidget* create (const QString& key, QWidget* parent = 0, const char* name = 0);
QString group (const QString& key) const;
QIconSet iconSet (const QString& key) const;
QString includeFile (const QString& key) const;
QString toolTip (const QString& key) const;
QString whatsThis (const QString& key) const;
bool isContainer (const QString& key) const;
};
Q_EXPORT_PLUGIN(PixmapButtonPlugin)
// PixmapButtonPlugin.cpp
#include "PixmapButtonPlugin.hpp"
#include "PixmapButton.qh"
QStringList PixmapButtonPlugin::keys () const
{
return QStringList() << "PixmapButton";
}
QWidget* PixmapButtonPlugin::create (const QString&, QWidget* parent, const char*)
{
return new PixmapButton(parent);
}
QString PixmapButtonPlugin::group (const QString&) const
{
return "Buttons";
}
QIconSet PixmapButtonPlugin::iconSet (const QString& key) const
{
return QWidgetPlugin::iconSet(key);
}
QString PixmapButtonPlugin::includeFile (const QString&) const
{
return "PixmapButton.qh";
}
QString PixmapButtonPlugin::toolTip (const QString&) const
{
return "Pixmap button";
}
QString PixmapButtonPlugin::whatsThis (const QString&) const
{
return "Button that takes the shape of its pixmap";
}
bool PixmapButtonPlugin::isContainer (const QString&) const
{
return false;
}
I have finally copied the compiled shared library libplugins.so in the folder
/usr/lib/qt3/plugins/designer
The designer doesn't display the plugins anywhere and doesn't tell me that it couldn't create the corresponding widget either. I get absolutely no error.
What should I do?
I got some help at work from a senior developer and actually found a way out of this problem. The main issue here is to make sure that the plugin is ok. How can I check that everything is fine with my plugin? That's pretty simple.
First, compile the following simple application:
// PluginLoader.cpp
#include <iostream>
#include <qlibrary.h>
#include <private/qcom_p.h>
int main(int argc, char *argv[])
{
QLibrary lib("/path-to-my-plugin/myPlugin.so");
std::cout << "Load: " << lib.load() << std::endl;
std::cout << "Resolve: " << (lib.resolve("ucm_instantiate") != 0) << std::endl;
return 0;
}
Second, activate some debugging tools for libraries: type the following commands in a console
export LD_WARN=1
export LD_VERBOSE=1
export LD_DEBUG=all
Note that there are many other options than "all" for the LD_DEBUG variable. Just type
export LD_DEBUG=help
to get more details (you will get the details as soon as you launch the above application).
Then, launch the PluginLoader application
./PluginLoader 2> loader.log
The file loader.log will then contain all the details regarding the libraries that are being loaded, in particular messages starting with
symbol lookup error
which indicate that something is missing in the plugin.
When the PluginLoader is happy, i.e. when it says
Load: 1
Resolve: 1
you are normally ready to use the plugin in the Qt Designer. To use it, copy it in the folder
/usr/lib/qt3/plugins/designer
or
$QTDIR/plugins/designer
which is the default folder for the designer's plugins. You may also be successful by setting the
LD_LIBRARY_PATH
QT_PLUGIN_PATH
appropriately.
Usually, you can also simply
ldd /path-to-your-plugin/myPlugin.so
This will show you which libraries this plugin was linked against. This can provide you with information about libraries that you may have forgotten ...
And a last comment. I am developing on SLES 11 SP3 64 bits. However, I am compiling 32-bits applications. In particular, the plugin is 32 bits. Before trying to let the plugin appear in the designer, make sure that the designer is the 32-bit version. Otherwise, the plugin won't appear in the list.
Note also that this process can also be applied to the production of Qt4 and Qt5 plugins (maybe modulo a few adaptions)!

unordered_map::find() and two iterators

Having a class with a private member
std::unordered_map<std::string, size_t> myMap;
and the corresponding getter
std::unordered_map<std::string, size_t> getMyMap() const {return myMap;}
I observe strange behaviour by applying std::unordered_map::find() two times, each time saving the returned iterator, e.g.
auto pos1 = test.getMyMap().find("a");
auto pos2 = test.getMyMap().find("a");
Altough I look for the same key "a" the iterator points to different elements. The following sample code illustrates the problem:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
class MyMap{
public:
MyMap(){
myMap= {
{"a", 1},
{"b", 2}
};
}
std::unordered_map<std::string, size_t> getMyMap() const {return myMap;}
private:
std::unordered_map<std::string, size_t> myMap;
};
int main(){
MyMap test;
auto pos1 = test.getMyMap().find("a");
auto pos2 = test.getMyMap().find("a");
std::cout << pos1->first << "\t" << pos1->second << std::endl;
std::cout << pos2->first << "\t" << pos2->second << std::endl;
}
Compiling with g++ -std=c++11 and running gives
b 2
a 1
where the first line is unexpected. It should be "a 1".
Changing the code to
auto pos3 = test.getMyMap().find("a");
std::cout << pos3->first << "\t" << pos3->second << std::endl;
auto pos4 = test.getMyMap().find("a");
std::cout << pos4->first << "\t" << pos4->second << std::endl;
results in the correct output
a 1
a 1
Furthermore just creating an unordered_map in the main file and applying find() works. It seems the problem is connected to the getter-method, maybe to return-value-optimisation. Do you have any explanations for this phenomena?
It's because you have undefined behavior in your code. The getMyMap returns a copy of the map, a copy that is destructed once the expression test.getMyMap().find("a") is done.
This means you have two iterators that are pointing to no longer existing maps.
The solution is very simple: Make getMyMap return a constant reference instead:
std::unordered_map<std::string, size_t> const& getMyMap() const;
That it seems to work in the latter case, is because that's a pitfall of undefined behavior, it might sometime seem like it works, when in reality it doesn't.
test.getMyMap().find("a"); does find on a copy of original myMap which is destructed after the expression is complete, making the iterators pos1 and pos2 to non-existing map, invoking an undefined behaviour
Instead you can play around like following :
auto mymap = test.getMyMap() ; // Store a copy
auto pos1 = mymap.find("a"); // Then do stuff on copy
auto pos2 = mymap.find("a");

c++ template char class

I can't find the problem. I am trying to use char as parameter for a class template:
#include <iostream>
using namespace std;
template <class Type1, class Type2> class myclass
{
Type1 i;
Type2 j;
public:
myclass(Type1 a, Type2 b) {i=a; j=b;}
void show() { cout << i << ' ' << j << '\n'; }
};
void main()
{
myclass<int, double> ob1(10, 0.23);
myclass<char, char *> ob2('X', Just show ");
ob1.show();
ob2.show();
}
You are missing an opening quote before Just:
myclass<char, char *> ob2('X', Just show ");
// ^
// should be:
myclass<char, char *> ob2('X', "Just show");
Note though that you should use const char* when you want to allow passing string literals and that this has ownership issues. Preferrably use std::string instead.
You are missing an " in myclass<char, char *> ob2('X', Just show ");, it should be myclass<char, char*> ob2('X', "Just show ");. Furthermore the type should probably myclass<char, const char*> instead of myclass<char, char*>