I am very new to C++-CLI and recently finished working on my first "official" application. I was advised to create application logs to track its effectiveness. When the form opens, the application tracks the date, time, and PC username and writes it to a text file.
That works well, though I am having trouble displaying an IP Address. I receive an error "Type name is not allowed" on (System::Net::IPAddress).
lastlineoffile += ( std::string((char *)Marshal::StringToHGlobalAnsi(DateTime::Now.ToString("MM-dd-yy")).ToPointer()) + " " +
std::string((char *)Marshal::StringToHGlobalAnsi(DateTime::Now.ToString("HH:mm")).ToPointer()) + " " +
//std::string((char *)Marshal::StringToHGlobalAnsi(System::Net::IPAddress).ToPointer()) + " " +
std::string((char *)Marshal::StringToHGlobalAnsi(System::Environment::UserName).ToPointer()) );
std::cout << "last line to be added: " << lastlineoffile << std::endl;
file << lastlineoffile.c_str();
//saves usage text file
file.close();
Additionally, I would like to record the time the application is exited. The previous perimeters are all recorded at the start of the application. I figure there would have to be a pointer that references the time off when the application closes. Any insight on how this would be accomplished would be appreciated.
Thanks
System::Net::IPAddress is the name of a class, not an object. It's a data storage class used for storing IP addresses. It's not an object you can pass to StringToHGlobalAnsi.
I'm guessing that you want to log your machine's IP address. OK, but which one? The computer I'm on right now has 6 of them, and would have more if I connected to a VPN. I'd follow the instructions in this question & answer to iterate over the IP addresses, and pick one, but you'll still have multiple if you have multiple network cards, whether real or virtual.
If all you need is a lightweight 'which machine is this' identifier, you may want to use Environment::MachineName. That will give you the current machine's name, as a string.
Other notes:
Standard warning: While it's certainly possible to write the main body of your application in C++/CLI, or even write the GUI in C++/CLI using WinForms, it is not recommended. C++/CLI is intended for interop scenarios: where C# or other .Net code needs to interface with unmanaged C++, C++/CLI can provide the translation between the two. For primary development, it is recommended to use C# with either WinForms or WPF if you want managed code, or C++ with MFC if you want unmanaged.
Related to that, if you're writing C++/CLI, I would prefer to use the higher-level language when you have a choice. Therefore, I would favor the .Net File I/O, rather than unmanaged io streams. You're already writing managed code, with a very full-featured standard library, you might as well use it!
StringToHGlobalAnsi is not the preferred way to convert from managed to unmanged strings. If you do want to use it, that's fine, but each call without a corresponding call to FreeHGlobal is a memory leak. The preferred way is to use marshal_as, as described in Overview of Marshaling in C++. With marshal_as, you can convert directly from String^ to std::string, and both classes manage their memory appropriately, so no memory leaks. (But using the higher-level language, and doing your logging with .Net classes, would be even better.)
Related
I'm playing around with an esp32 (c with esp-idf, not with arduino) for a hobby project of mine. I'm currently programming a little drone that I can control with my smartphone. All works well.
But now I need to create system for persistent settings and parameters. For example pid-tuning parameters or what sensors are enabled and more. The general idea was to have a settings file in flash that is read on startup. The settings can then be used in the individual modules of the program. Now I'd also like to change those settings during runtime. For example pid tuning parameters. I don't want to reboot the system only to change a small parameter.
So now my question: How can I handle changes to those settings during runtime?
An idea was to have the module periodically ask a special
"settings-module" if there are any changes. It would then change its
internal settings accordingly. As settings shouldn't change that
often I think the overhead of constantly asking for updates is rather
unnecessary.
A more extreme idea was, to give a pointer to the variable in
question to the "settings-module". If any changes have to be made the
settings module would change the variable directly.
Or maybe a callback system?
The ideas seem feasible but I don't know if there are any best-practices or better options.
Does anyone of you know a name of a technique I can google or maybe an library that provides something similar?
Thanks!
ESP ISF already has 90% of your requirements covered with the non-volatile storage library - string keys, int/string values, wear levelling etc. Just use this to store all your settings and parameters. Read from it every time you want to get a value (unless you go to the sub-millisecond latency land, in which case it's perhaps best to cache the settings in RAM).
Reading a value from NVS can fail (e.g. if the parameter is not stored, the NVS partition got wiped, etc) which would introduce cumbersome error handling into every code block where you read a parameter. A common trick to avoid this error handling is to add a thin wrapper which takes a fallback value of the parameter and returns it every time reading the parameter from NVS fails. Something like this:
uint32_t fetchU32(const char* key, const uint32_t fallback) {
uint32_t ret;
if (ESP_OK != nvs_get_u32(g_nvs_hnd, key, &ret)) {
ret = fallback;
}
return ret;
}
Note that you need to be careful when using such wrappers - occasionally a critical parameter value must be found from NVS and not replaced with a fallback blindly.
Adding to what Tarmo suggested, you should also take not there are write limits to the ESP32's NVS. But do take note that the limits are set by what flash you are using.
I am placing this link where they discuss the write limits of the ESP32.
I have a c code with a character array initialized to "hello world".
I would like to know if there is a possibility to re-initialize this character array upon each execution of the code, to some other random string. If not C, may I know if such an implementation is possible in any other programming language?
In detail, let's say my code looks like:
char c[] = "hello world";
.
.
After executing this code once, I want the char array c to be initialized automatically to some other random string (and not "hello world") and this should be a permanent change. This need is for security reasons. May I know if such a thing is even possible?
If not, may I know if it is possible to let the code self-destroy after executing it once?
It would be much easier to answer this question if you could describe what you are trying to achieve, rather than a particular mechanism you thought of to achieve it.
Modifying the running executable is typically prevented by modern operating systems, and for good reasons (security, integrity, etc). And modifying the executable on-disk is also inadvisable, for similar reasons. I'm sure there are other ways to achieve what you wish without resorting to self-modifying code.
I have a c code with a character array initialized to "hello world'. I would like to know if there is a possibility to re-initialize a this character array upon each execution of the code, to some other random string.
Yes, it's possible, but you would need to give the user write access to the executable to do so, find the correct offset in the binary, patch the file and save it intact atomically, etc, etc. There are many ways this can go wrong. Don't do it this way.
Instead of a statically allocated string in the executable itself, just have a separate resource file that contains the string(s) and whatever other state is required. You can change this resource file (INI file, data file, whatever) to modify the string as and when required (or even delete it). To provide security, you can digitally sign the file, which allows you to verify the contents are legitimate. If the signature fails, the software can refuse to work. You can also encrypt the contents so that it cannot be read out by an inquisitive user. (Unless they are handy with a debugger!)
If not C, may I know if such an implementation is possible in any other programming language?
It's mainly an OS restriction, including a regular user being able to write to an installed app in a system folder (typically something you do not want to allow). And if you can't do it in C, you probably can't do it in another language!
After executing this code once, I want the char array c to be initialized automatically to some other random string (and not "hello world") and this should be a permanent change. ... May I know if such a thing is even possible?
Yes indeed, but use a separate file as described above. Don't modify the executable itself.
This need is for security reasons.
The reason self-modifying code is disallowed in the first place is for security reasons. If you are attempting to implement some kind of copy protection, you would do well to research existing methods and tools and best practices, and possibly even use an off-the-shelf solution. This stuff is hard, and there are people who crack software for fun who could easily get around all but the most sophisticated protection schemes.
If not, may I know if it is possible to let the code self-destroy after executing it once?
You might be able to get the executable to delete itself, but this would typically require elevated privileges too.
Just get the program to check the signature on the resource file and refuse to run if it isn't valid.
You can self modify a EXE file, but you need to know:
You are basically reinventing the wheel doing it that way
Self modifying code is usually (in fact, most likely) flagged by antivirus software. Destroying the EXE after it is executed is even more shady.
How EXE (and ELF) files are executed
What the assembly language is
So I've run into an interesting design pattern and I wanted to know if you guys had an opinion on it.
Basically, the design is passing everything around as a pre-serialized type. There is no "types" for the returns, for example. It is passed as a simple uint8_t*. There is a defined header that "tells" you what is in the buffer, how big it is, what the version of the buffer is, ect. I call it "pre-serialized" because it forces flattening of all structures.
The pros:
You can easily write it (or even a set of it) to what ever you want. Files, IO, whatever.
Can store arbitrary data.
The Cons: IMHO:
No type safety is going to be a nightmare
The programmer has to parse the code. Even if there is an enumerated type, the user would have to know what that type means. Even if there are functions to parse the type, the programmer has to know that is the function to call.
Version hell: changing code will cause a ripple effect of errors. Because everywhere is parsing it differently, you have no idea where the code works or where it is broken.
It is viral: because it is flat, you can't "insert" the header on the end of outside data. You could wrap the call if you copy your "data", but this could cause an unnecessary copy that would be SLOW. So either your code is slower than it needs to be, or you conform to this data structure.
It isn't human readable OR debug-able.
Have you seen this design pattern before? Is there a name for this design pattern? Things I missed?
Is there a name for this design pattern?
Well, Legacy Code? :) I have seen such design in 30 years old Cobol systems...
The pros you have stated are easily reachable also by using XML format (or JSON):
You can easily write it (or even a set of it) to what ever you want. Files, IO, whatever - most of all, web services!
Can store arbitrary data.
Furthermore, all your cons are eliminated.
The only pro I can see in your solution is conciseness - when every byte counts and you need to avoid any overhead as too expensive, then this is nice.
Added: Cobol has a feature to easily define the structure of such serialized data, see PICTURE clause. Reading the data is very easy then, you read them as variables. (Like if you have a binary data and define a struct in the C language and typecast the binary to the struct.)
As Honza said this would be normal in Legacy Cobol/PL1 (was there a Cobol/PL1 conversion or interface to COBOL programs ???).
In COBOL this design pattern would make sense, not sure about C though (one of the binary serialization packages or JSON etc might be more sensible).
In Cobol, you would have a Cobol copybook which all programs would use and could edit the data using the Cobol Copybook (with something like file-aid or Microfocus Data Editor).
Why use this "design pattern" in Cobol:
Regression testing of Modules; you can write a driver module like
Read Test-data-file
while more-data
Call Module
write Result to output-file
Read Test-data-file
end
You can then do a compare between Output from the
re-Change Program to the changed program.
Testing - some times you can use a "production file" in testing
A file provides trace or snapshot of what is going on, this can be very useful.
Easy to reorganize Batch streams:
Split a programs up (and pass the data via file). There variety of reason for doing this including
program has gotten to big and is hard to maintain.
Sorting the data
Performance (use a file rather than hitting the DB multiple times)
new uses for extracted data
While your cons are valid for C, they will be less of an issue in Cobol.
The key to using this "design pattern" is being able to edit/view/compare the format. If you can not edit/view/compare a file, I do not see the point
Currently, on my embedded system (coded in C), I have a lot of debug-assistive print statements which are executed when a remote tool is hooked up to the system that can display the messages to a PC. These help to understand the general system status, but as the messages are going over a slow CAN bus, I believe they may be clogging the tubes and causing other problems with trying to get any useful data logged.
The basic gist of it is this:
It's like a printf, but ultimately in a special message format that gets sent from the embedded system to the tool over the CAN bus. For this purpose, I can replace this generic print message with special debugging messages that send it a unique ID followed by only the variable parameters (i.e. the argc/argv). I am wondering if that is the right way to go about it, or if there is a magic bullet I've missed, or something else I haven't thought of.
So, I found this question which starts out well for my purposes:
printf() debugging library using string table "decoder ring"
But I do not have the constraint of making it as easy as a printf. I can maintain a table of strings on the remote tool's side (since it's a Windows executable and therefore not as code size limited). I am the sole person responsible for this code and would prefer to try and lighten up the code size as well as the CAN bus traffic while debugging.
My current thoughts are thus:
printf("[%d] User command: answer call\n", (int)job);
This becomes
debug(dbgUSER_COMMAND_ANSWER_CALL, job);
dbgUSER_COMMAND_ANSWER_CALL being part of an enum of possible debug messages
and the remote side has something like
switch(messagetype)
{
case dbgUSER_COMMAND_ANSWER_CALL:
/* retrieve an integer from the data portion of the message and put it into a variable */
printf("[%d] User command: answer call\n", (int)avariable);
}
That's relatively straightforward and it would be fantastic if all my messages came in that same format. Where it gets tricky, though, is where some of my statements have to print strings which are not constant (the name of the device, for example).
printf("[%d] %02X:%02X:%02X:%02X:%02X:%02X (%s)\n", /* a bunch of parameters here */);
So, should I make it so that the contents of the debug message are 1) the message type, 2) length of the first parameter, 3) the parameter, 4) length of the next parameter, 5) the parameter, so on and so forth
Or have I overlooked something more obvious or easy?
Thanks
I'm assuming you use CAN because that's the connection you already have to your device. You haven't really provided enough information about your diagnostic needs, but I can give an example of what we do where I work. We use a custom build tool to comb through our sources building up a string table. Our code uses something like:
log( LOGH(T0722T), //"Position"
LOG_DOT_HEX_VALUE(i),
LOG_TEXT(T0178T), //"Id"
LOG_DOT_VALUE(uniqueId % 10000),
0 );
This would record some data which could be decoded into:
<timestamp> H Position.00B Id.0235
We allow use of T0000T to have the tool lookup (or generate) a unique number for us. The tool builds up an enum using the TxxxxT numbers for the compiler, and a file containing the ordered list of strings. Every build generates a string table which matches the enum numbering. This system also ties into a database system used for generating internationalized strings, but that's not really relevant to your question.
Each element is a short (16 bits). We allow 12 bits for values and use the high 4 bits for type and flag info. Is the encoded data a string id; Is it a signal (High/Low) or just an event; Is it a value; Is it decimal, hexidecimal, base64url; concatenated (with the preceding item) or separate.
We record data in a large ring buffer for querying if needed. This allows the system to run without interference but the data can be extracted if a problem is noted. It is certainly possible to constantly send the data, and if that's desired I'd suggest limiting any one message to a single CAN payload (that's 8 bytes assuming you only use a single ID). The message I provided above would fit in one CAN message if properly encoded (assuming the receiving side created the timestamps).
We do have the ability to include arbitrary data (ASCII or Hexadecimal), but I never use it. It's usually a waste of precious space in the logs. Logging is always a balance in embedded environments.
Obviously, this information is available in xorg.conf so I could try to parse this file. But is there a way to achieve this using Xlib calls (+ extensions) only?
Thanks,
PMJ
It must be possible, because I know the program xdpyinfo can do it. At first, I was going to suggest executing that from within your program and parsing the output. That shouldn't be necessary, though, since the source of xdpyinfo is freely available.
It looks like if you have a (Display*) variable (and you will, because pretty much every X11 function call requires one), you can call these wonderful macros to get interesting data, including ServerVendor and VendorRelease. That should cover the "graphic adapter" portion of your quest.
As for the monitor name, according to xdpyinfo.c, this is governed by XF86VidModeGetMonitor() which is part of an X11 extension. This returns a XF86VidModeMonitor structure which will reveal vendor, model, and other juicy data.
Run xdpyinfo-- if that program can query the data, so can your program.