Access to OS functions from CAPL - operating-system

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;
}

Related

How to use running status with midiOutShortMsg?

As described here, it should be possible to omit the status byte and only send data bytes after I set the status byte by sending the first command.
I'm testing with NoteOn command code (90 hex) and trying to play a chord, but it only works when the status byte is set at each call.
I tried putting the tone number into the lowest byte and velocity into second lowest but no sound was produced...
What you describe sounds correct, however, if you are not getting the expected result then it's possible your MIDI device is not fully MIDI compliant.
The following example code successfully plays a broken chord using running status on the Windows built-in MIDI device on my Windows 11 machine:
#pragma comment(lib, "Winmm.lib")
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <mmsystem.h>
#include <mmeapi.h>
#include <iostream>
int main()
{
try
{
HMIDIOUT hMidiOut = 0;
MMRESULT mmResult = midiOutOpen(&hMidiOut, -1, NULL, NULL, CALLBACK_NULL);
if (mmResult != MMSYSERR_NOERROR)
throw std::exception("Failed to open the MIDI device.");
mmResult = midiOutShortMsg(hMidiOut, 0x007F4090);
if (mmResult != MMSYSERR_NOERROR)
throw std::exception("midiOutShortMsg() failed.");
Sleep(500);
mmResult = midiOutShortMsg(hMidiOut, 0x00007F42);
if (mmResult != MMSYSERR_NOERROR)
throw std::exception("midiOutShortMsg() failed.");
Sleep(500);
mmResult = midiOutShortMsg(hMidiOut, 0x00007F44);
if (mmResult != MMSYSERR_NOERROR)
throw std::exception("midiOutShortMsg() failed.");
Sleep(3000);
midiOutReset(hMidiOut);
midiOutClose(hMidiOut);
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
}

How to display the result of function called using object reference in c++

#include "pch.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdio.h>
using namespace std;
class LetterDistribution
{
public: char district, trace;
public: int random_num;
public : LetterDistribution(){}
public: LetterDistribution(char dis)
{
district = dis;
trace = 'Z';
}
public: string LetterNumbers()
{
random_num = rand();
string letter_no ( district + " " + random_num);
return letter_no;
}
};
int main()
{
srand(time(0));
cout << "Enter district\n"<<endl;
char dis ;
cin >> dis;
LetterDistribution ld(dis);
cout << ld.LetterNumbers();
return 0;}
I am getting error in second last line inside main "cout << ld.LetterNumbers();". I am new to c++ , I have been working on C# earlier. I shall be thankful if someone could help me .
You have 2 issues in LetterNumbers function:
You can't add to string a number, you should convert the number to string first. you can do so by std::to_string(random_num)
You can't start concatenate string with a character, since character is like number in c++, and adding anything to number is a number. You should start from a string, even an empty one.
So the whole function can be something like:
string LetterNumbers()
{
random_num = rand();
string letter_no ( std::string("") + district + " " + std::to_string(random_num));
return letter_no;
}
Another issues: (but not errors!)
in c++ you can specify public: once, and everything after it is still public, until you change it. same thing for private and protected.
instead of <stdio.h> you should use <cstdio> which is the c++ wrapper for the c header.

Behavior of select() on stdin when used on a pipe

I am trying to understand an observation on behavior of select() when used on stdin, when it is receiving data from a pipe.
Basically I had a simple C program using the following code:
hello.c:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <termios.h>
int main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
fd_set rfds;
struct timeval tv;
int retval;
int stdin_fileno_p1 = STDIN_FILENO+1;
char c;
int n;
/* Turn off canonical processing on stdin*/
static struct termios oldt, newt;
tcgetattr( STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON);
tcsetattr( STDIN_FILENO, TCSANOW, &newt);
while (1)
{
FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
retval = select(stdin_fileno_p1, &rfds, NULL, NULL, &tv);
if ( retval && (retval!=-1) )
{
n = read(STDIN_FILENO, &c, 1);
write(STDOUT_FILENO, &c, 1);
}
else printf("No Data\n");
usleep(100000);
}
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}
If I ran the program as follows I could see characters echoing when I type keys on while the program is running. When keys are not pressed, it displays "No Data" as expected.
./hello
However, if use the program as follows, the program never gets to a state where is displays "No Data". Instead last character "c" is repeatedly displayed.
echo -n abc | ./hello
I'm a bit puzzled by this observation, and would be grateful if you could help me to understand the observed behavior.
The problem is that your program does not detect an end-of-file condition when it reads from the STDIN_FILENO descriptor. After echo has written the c character it will close its end of the pipe, which will cause the select in your program to return immediately and your read to return 0 as an indication that no more data will ever be available from that descriptor. Your program doesn't detect that condition. Instead it just calls write with whatever character was left in the buffer by the last successful read and then repeats the loop.
To fix, do if (n==0) break; after the read.

error: request for member 'find' in '(cstring name)' which is of non-class type 'char [2000]'

I'm sorry if this is vague I'm still pretty new to programming(also new to forums >_>)
Ok, my code is supposed to read in a number from a file, then use that number to read in that amount of words as dictionary words. I then store those words into an array and keep them for later usage. After the dictionary words in the file comes some paragraph, i read that in and set it to c-string array.(iv got that all down so far) But for the last part of the program i need to go back though that paragraph c-string and count how many times each dictionary word appears. I'm currently trying paragraph.find (word[0]) but i get some error that i don't know how to fix.
error: |40|error: request for member 'find' in 'paragraph', which is of non-class type 'char [2000]'|
code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <windows.h>
using namespace std;
int main()
{
ifstream inStream; //declare ifstream
inStream.open("infile2.txt"); //open my file
int number; // number at the begining of the file that lets the program know
inStream >> number; // how many dictionary words are to be expected.
cout << number << " dictionary word(s)" << endl << endl;
char dict[30];
char text[2000];
char paragraph[2000]; // declareing some stuff
int count;
int position;
string word[5];
for (int i=0; i<number; i++) // using c string to set the 'number' amount of words in the dict array
{
inStream.getline(dict,30,'|');
word[i] = dict;
}
for (int i=0; i<number; i++) // cout so i can see its all set up right.
{
cout << "word " << i+1 << " is: " << word[i] << endl;
}
cout << endl;
inStream.get(paragraph,2000,'|'); // setting the rest of the paragrapg of the txt document to a c string
cout << paragraph; // so it can be searched later using the 'dict' words
position = paragraph.find (word[0]); // trying to find the position of the first word stored in 'dict[0]' but i run into an error
return 0;
}
the infile2.txt looks like this:
3steak|eggs|and|
steak and eggs and eggs and steak, eggs and steak, steak and eggs...
delicious.
c-strings are not classes and do not have a find method (or any other methods for that matter) i.e paragraph.find. You could try using a string or if you need to use c-strings a find method that takes two c strings as parameters.
such as This one

Command line parser for Qt4

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.