Modify Code through a GUI - c++

Hey this is more of a question, i want to know if it is possible to modify code through GUI asking because i was asked to see if i could create a GUI where the user can change certain attributes. i.e an exmaple is below
start %= -(status)
> lexeme[elementV]
> -(lexeme[elementF])
> +(inboundGroup);
Above is part of my code which is Boost SPIRIT which parses Strings so for example would it be possible to change the + to a * or - etc
+ = One
- = optional
* = multiple
Do you think it would be possible to change that through a GUI i think it could be just not sure on how to do it?
Any help i will be very grateful
Thanks Shamari

Everything is possible in programming ;-)
For dynamic modification of a program during execution, there are several solutions :
Use a dynamic language like LUA
Use a plugin system with dynamic loading
Since you require C++ and Boost Spirit, I think the best solution is to generate a plugin on the fly and load it afterwards.
Your program will generate code, compile it into a shared library (.so) and then load and execute it. (Some people will find that dirty. It's insecure also. But it's simple and it works.)
Here is an exemple for linux : plugin.h :
#ifndef PLUGIN_H__
#define PLUGIN_H__
#ifdef __cplusplus
extern "C" {
#endif
int process();
typedef int (*plugin_process_fn_ptr)();
#ifdef __cplusplus
}
#endif
#endif // PLUGIN_H__
Note that we must use extern C or else, C++ name mangling will make it difficult to import symbols.
plugin.cpp :
#include "plugin.h"
#include <iostream>
using namespace std;
int process()
{
int return_value = 0;
#include "plugin_content.inc.cpp"
return return_value;
}
Note that I use a hack here, the code will be included from another file, "plugin_content.inc.cpp". The code from user will be put inside.
a script to build the plugin, "build_plugin.sh" :
#! /bin/sh
g++ -c -Wall -fPIC plugin.cpp -o plugin.o
gcc -shared -o libplugin.so plugin.o
Now the calling program, main.cpp :
#include <iostream>
#include <fstream> // to open files
#include <dlfcn.h> // C lib to load dynamic libs
#include "plugin.h"
using namespace std;
// load the plugin and call the process() function fom it
static int process_via_plugin()
{
int return_value = -1;
void *lib_handle(NULL);
char *error(NULL);
char *plugin_lib = "./libplugin.so";
lib_handle = dlopen(plugin_lib, RTLD_LAZY);
if (!lib_handle)
{
cerr << "Error loading lib " << plugin_lib << " : " << dlerror() << endl;
exit(1);
}
char *plugin_fn = "process";
plugin_process_fn_ptr fn = (plugin_process_fn_ptr)dlsym(lib_handle, plugin_fn);
error = dlerror();
if (error)
{
cerr << "Error finding lib " << plugin_fn << " : " << error << endl;
exit(1);
}
// call the function loaded from lib
return_value = (*fn)();
dlclose(lib_handle);
lib_handle = NULL; // useless but for good habits ^^
return return_value;
}
// build or rebuild the plugin,
// we must call it when we change the plugin code code
static int build_plugin(string code)
{
{
char *plugin_code_file = "plugin_content.inc.cpp";
ofstream plugin_code(plugin_code_file, ios::out);
plugin_code << code << endl;
}
system("build_plugin.sh");
return 0;
}
// our program
int main(int argc, char *argv[])
{
cout << "Hello World !" << endl;
string code = ""
"cout << \"Hello from plugin !\" << endl;"
"";
// build a first version of the plugin and call it
build_plugin(code);
process_via_plugin();
// now we modify the code (use a GUI here)
code = ""
"cout << \"Hello from plugin, updated !\" << endl;"
"";
// rebuild the plugin and call it again
build_plugin(code);
process_via_plugin();
// do it again as much as you want.
return 0;
}
Now, build your program :
g++ -Wall -rdynamic -ldl main.cpp
and execute it :
a.out
and you get :
Hello World !
Hello from plugin !
Hello from plugin, updated !
The code I give you is very basic. For example, we should check if the compilation of the plugin is successful and report errors to the user. Now it's up to you to add more stuff.

Related

How do change the default directory for file creation? [duplicate]

How can I change my current working directory in C++ in a platform-agnostic way?
I found the direct.h header file, which is Windows compatible, and the unistd.h, which is UNIX/POSIX compatible.
The chdir function works on both POSIX (manpage) and Windows (called _chdir there but an alias chdir exists).
Both implementations return zero on success and -1 on error. As you can see in the manpage, more distinguished errno values are possible in the POSIX variant, but that shouldn't really make a difference for most use cases.
Now, with C++17 is possible to use std::filesystem::current_path:
#include <filesystem>
int main() {
auto path = std::filesystem::current_path(); //getting path
std::filesystem::current_path(path); //setting path
}
For C++, boost::filesystem::current_path (setter and getter prototypes).
A file system library based on Boost.Filesystem will be added to the standard.
This cross-platform sample code for changing the working directory using POSIX chdir and MS _chdir as recommend in this answer. Likewise for determining the current working directory, the analogous getcwd and _getcwd are used.
These platform differences are hidden behind the macros cd and cwd.
As per the documentation, chdir's signature is int chdir(const char *path) where path is absolute or relative. chdir will return 0 on success. getcwd is slightly more complicated because it needs (in one variant) a buffer to store the fetched path in as seen in char *getcwd(char *buf, size_t size). It returns NULL on failure and a pointer to the same passed buffer on success. The code sample makes use of this returned char pointer directly.
The sample is based on #MarcD's but corrects a memory leak. Additionally, I strove for concision, no dependencies, and only basic failure/error checking as well as ensuring it works on multiple (common) platforms.
I tested it on OSX 10.11.6, Centos7, and Win10. For OSX & Centos, I used g++ changedir.cpp -o changedir to build and ran as ./changedir <path>.
On Win10, I built with cl.exe changedir.cpp /EHsc /nologo.
MVP solution
$ cat changedir.cpp
#ifdef _WIN32
#include <direct.h>
// MSDN recommends against using getcwd & chdir names
#define cwd _getcwd
#define cd _chdir
#else
#include "unistd.h"
#define cwd getcwd
#define cd chdir
#endif
#include <iostream>
char buf[4096]; // never know how much is needed
int main(int argc , char** argv) {
if (argc > 1) {
std::cout << "CWD: " << cwd(buf, sizeof buf) << std::endl;
// Change working directory and test for success
if (0 == cd(argv[1])) {
std::cout << "CWD changed to: " << cwd(buf, sizeof buf) << std::endl;
}
} else {
std::cout << "No directory provided" << std::endl;
}
return 0;
}
OSX Listing:
$ g++ changedir.c -o changedir
$ ./changedir testing
CWD: /Users/Phil
CWD changed to: /Users/Phil/testing
Centos Listing:
$ g++ changedir.c -o changedir
$ ./changedir
No directory provided
$ ./changedir does_not_exist
CWD: /home/phil
$ ./changedir Music
CWD: /home/phil
CWD changed to: /home/phil/Music
$ ./changedir /
CWD: /home/phil
CWD changed to: /
Win10 Listing
cl.exe changedir.cpp /EHsc /nologo
changedir.cpp
c:\Users\Phil> changedir.exe test
CWD: c:\Users\Phil
CWD changed to: c:\Users\Phil\test
Note: OSX uses clang and Centos gnu gcc behind g++.
Does chdir() do what you want? It works under both POSIX and Windows.
You want chdir(2). If you are trying to have your program change the working directory of your shell - you can't. There are plenty of answers on SO already addressing that problem.
Did you mean C or C++? They are completely different languages.
In C, the standard that defines the language doesn't cover directories. Many platforms that support directories have a chdir function that takes a char* or const char* argument, but even where it exists the header where it's declared is not standard. There may also be subtleties as to what the argument means (e.g. Windows has per-drive directories).
In C++, googling leads to chdir and _chdir, and suggests that Boost doesn't have an interface to chdir. But I won't comment any further since I don't know C++.
Nice cross-platform way to change current directory in C++ was suggested long time ago by #pepper_chico. This solution uses boost::filesystem::current_path().
To get the current working directory use:
namespace fs = boost::filesystem;
fs::path cur_working_dir(fs::current_path());
To set the current working directory use:
namespace fs = boost::filesystem;
fs::current_path(fs::system_complete( fs::path( "new_working_directory_path" ) ));
Bellow is the self-contained helper functions:
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include <string>
namespace fs = boost::filesystem;
fs::path get_cwd_pth()
{
return fs::current_path();
}
std::string get_cwd()
{
return get_cwd_pth().c_str();
}
void set_cwd(const fs::path& new_wd)
{
fs::current_path(fs::system_complete( new_wd));
}
void set_cwd(const std::string& new_wd)
{
set_cwd( fs::path( new_wd));
}
Here is my complete code-example on how to set/get current working directory:
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include <iostream>
namespace fs = boost::filesystem;
int main( int argc, char* argv[] )
{
fs::path full_path;
if ( argc > 1 )
{
full_path = fs::system_complete( fs::path( argv[1] ) );
}
else
{
std::cout << "Usage: tcd [path]" << std::endl;
}
if ( !fs::exists( full_path ) )
{
std::cout << "Not found: " << full_path.c_str() << std::endl;
return 1;
}
if ( !fs::is_directory( full_path ))
{
std::cout << "Provided path is not a directory: " << full_path.c_str() << std::endl;
return 1;
}
std::cout << "Old current working directory: " << boost::filesystem::current_path().c_str() << std::endl;
fs::current_path(full_path);
std::cout << "New current working directory: " << boost::filesystem::current_path().c_str() << std::endl;
return 0;
}
If boost installed on your system you can use the following command to compile this sample:
g++ -o tcd app.cpp -lboost_filesystem -lboost_system
Can't believe no one has claimed the bounty on this one yet!!!
Here is a cross platform implementation that gets and changes the current working directory using C++. All it takes is a little macro magic, to read the value of argv[0], and to define a few small functions.
Here is the code to change directories to the location of the executable file that is running currently. It can easily be adapted to change the current working directory to any directory you want.
Code :
#ifdef _WIN32
#include "direct.h"
#define PATH_SEP '\\'
#define GETCWD _getcwd
#define CHDIR _chdir
#else
#include "unistd.h"
#define PATH_SEP '/'
#define GETCWD getcwd
#define CHDIR chdir
#endif
#include <cstring>
#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
string GetExecutableDirectory(const char* argv0) {
string path = argv0;
int path_directory_index = path.find_last_of(PATH_SEP);
return path.substr(0 , path_directory_index + 1);
}
bool ChangeDirectory(const char* dir) {return CHDIR(dir) == 0;}
string GetCurrentWorkingDirectory() {
const int BUFSIZE = 4096;
char buf[BUFSIZE];
memset(buf , 0 , BUFSIZE);
GETCWD(buf , BUFSIZE - 1);
return buf;
}
int main(int argc , char** argv) {
cout << endl << "Current working directory was : " << GetCurrentWorkingDirectory() << endl;
cout << "Changing directory..." << endl;
string exedir = GetExecutableDirectory(argv[0]);
ChangeDirectory(exedir.c_str());
cout << "Current working directory is now : " << GetCurrentWorkingDirectory() << endl;
return 0;
}
Output :
c:\Windows>c:\ctwoplus\progcode\test\CWD\cwd.exe
Current working directory was : c:\Windows
Changing directory...
Current working directory is now : c:\ctwoplus\progcode\test\CWD
c:\Windows>

luaL_dofile fails on known-good bytecode, works with uncompiled version

I've put together a very simple Lua engine but it seems to reject bytecode which works in the lua console. The uncompiled version works in the engine. Am I using luac wrong somehow?
I compile using the given command and run as './a.out'.
res/default.lua:
print("Setting up world structure.")
luac command:
luac -o res/default.lux res/default.lua
MWE:
#define SCRIPTDIR "res/"
#define THROW_IF_NONZERO(x,m) if((x)!=0) throw std::runtime_error(m);
#define THROW_IF_ZERO(x,m) if((x)==0) throw std::runtime_error(m);
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include "sys/stat.h"
#include <string>
#include <system_error>
#include <iostream>
using std::string;
class Entity {
private:
lua_State *m_lua;
public:
Entity() : Entity(nullptr) { }
Entity(lua_State *lua) : m_lua{lua} { }
virtual ~Entity() { }
void load_and_run(string);
};
class WorldEntity : public Entity {
public:
WorldEntity(lua_State *lua) : Entity(lua) {
luaL_openlibs(lua);
}
~WorldEntity() { }
};
int main() {
lua_State *lua{nullptr};
try {
lua = luaL_newstate();
WorldEntity eWorld{lua};
eWorld.load_and_run("default"); // load default.lua/lux
} catch(std::exception &e) {
if (lua != nullptr) {
lua_close(lua);
}
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}
void Entity::load_and_run(string filename) {
THROW_IF_ZERO(m_lua, "Lua not started.");
filename = SCRIPTDIR + filename + ".lux";
struct stat sb;
int rc = stat(filename.c_str(), &sb);
if (rc == -1) {
filename.pop_back();
filename += "a";
rc = stat(filename.c_str(), &sb);
THROW_IF_NONZERO(rc, "File not found!");
}
std::cout << "File: " << filename << std::endl;
// Currently won't run compiled Lua scripts, not sure why.
rc = luaL_dofile(m_lua, filename.c_str());
THROW_IF_NONZERO(rc, "Could not load lua file.");
}
compile command:
gcc src/bug001mwe.cpp -std=c++14 -llua -lstdc++
correct output from script:
File: res/default.lua
Setting up world structure.
wrong output from bytecode:
File: res/default.lux
Error: Could not load lua file.
both files, output from lua console:
Setting up world structure.
What confused me was that it worked in the lua console but not in my program. I added a call to lua_tostring after the call to luaL_dofile, like this:
rc = luaL_dofile(m_lua, filename.c_str());
std::ostringstream ostr;
ostr << "Could not load lua file. ";
ostr << lua_tostring(m_lua, -1);
THROW_IF_NONZERO(rc, ostr.str());
The error string became:
Error: Could not load lua file. res/default.lux: version mismatch in precompiled chunk
What the heck?
Long story short, I had a previous version of Lua installed due to out of date package dependencies in some unrelated stuff. The older luac was intercepting the luac command and compiling to valid but incompatible bytecode. Uninstalled the unrelated packages which I didn't really need, and now everything works.
Moral of the story: always check for an error string on the Lua stack, it will (probably) tell you what's wrong.

c++ loading dylib functions at runtime error

So I'm trying to load a .dylib file at runtime in c++ and calling a function within it. It does not seem to be any problem loading the file but when i try to create a function-pointer to the "print" function it's result is NULL.
Here is my code:
/* main.cpp */
#include <iostream>
#include <string>
#include <dlfcn.h>
#include "test.hpp"
int main(int argc, const char * argv[]) {
std::string path = argv[0];
std::size_t last = path.find_last_of("/");
// get path to execution folder
path = path.substr(0, last)+"/";
const char * filename = (path+"dylibs/libtest.dylib").c_str();
// open libtest.dylib
void* dylib = dlopen(filename, RTLD_LAZY);
if (dylib == NULL) {
std::cout << "unable to load " << filename << " Library!" << std::endl;
return 1;
}
// get print function from libtest.dylib
void (*print)(const char * str)= (void(*)(const char*))dlsym(dylib, "print");
if (print == NULL) {
std::cout << "unable to load " << filename << " print function!" << std::endl;
dlclose(dylib);
return 2;
}
// test the print function
print("Herro Word!");
dlclose(dylib);
return 0;
}
test dylib headerfile
/* test.hpp */
#ifndef test_hpp
#define test_hpp
void print(const char * str);
#endif
the dylib c++ file
#include <iostream>
#include "test.hpp"
void print(const char * str) {
std::cout << str << std::endl;
}
the output when running is:
unable to load /Users/usr/Library/Developer/Xcode/DerivedData/project/Build/Products/Debug/dylibs/libtest.dylib print function!
Program ended with exit code: 2
I am quite new to c++ and have never loaded dylibs before. Any help would be much appreciated!
Try qualifying the print function declaration with extern "C" to get around the name mangling that is likely going on.
Here's a nice article on the topic: http://www.tldp.org/HOWTO/C++-dlopen/theproblem.html (solution discussion on page following)

C++ DevIL function ilLoadImage - program exit, access violation

I've got a path to my file defined this way:
const char* GROUND_TEXTURE_FILE = "objects/textures/grass.jpg";
And here is the function, which I use to load image:
bool loadTexImage2D(const string &fileName, GLenum target) {
...
// this will load image data to the currently bound image
// at first, we must convert fileName, for ascii, this method is fine?
wstring file(fileName.begin(), fileName.end());
if(ilLoadImage(file.c_str()) == IL_FALSE) { //here the program falls
What's wrong in my code? Why the program falls when ilLoadImage is called? I think, that file.c_str() should work fine as a wchar_t * type or not? Thanks for answer :)
As the author's said, you can do pretty anything without initializing the lib :D
#include <iostream>
#include <IL/il.h>
int main ()
{
std::string filename = "objects/textures/grass.jpg";
ilInit();
if (!ilLoadImage(filename.c_str())) {
std::cout << ilGetError() << std::endl;
return 1;
}
std::cout << ilGetInteger(IL_IMAGE_WIDTH) << std::endl;
std::cout << ilGetInteger(IL_IMAGE_HEIGHT) << std::endl;
return 0;
}
build:
g++ -Wall -pedantic --std=c++11 -g -o app main.cpp -lIL

How to Get the Filename of the Currently Running Executable in C++ [duplicate]

This question already has answers here:
Get path of executable
(25 answers)
Closed 4 years ago.
I want to get the full path of the current process.
I use _getcwd to get the current working directory. But it not includes file name.
How can I get file name like: filename.exe?
argv[0] of your main function is your filename.
A simple code snippet:
#include<stdio.h>
int main(int argc, char** argv)
{
//access argv[0] here
}
If you cannot access/change code in main(), you can do something like this:
std::string executable_name()
{
#if defined(PLATFORM_POSIX) || defined(__linux__) //check defines for your setup
std::string sp;
std::ifstream("/proc/self/comm") >> sp;
return sp;
#elif defined(_WIN32)
char buf[MAX_PATH];
GetModuleFileNameA(nullptr, buf, MAX_PATH);
return buf;
#else
static_assert(false, "unrecognized platform");
#endif
}
On windows you can use:
TCHAR szExeFileName[MAX_PATH];
GetModuleFileName(NULL, szExeFileName, MAX_PATH);
szExeFileName will contain full path + executable name
[edit]
For more portable solution use argv[0] or some other platform specific code. You can find such aproach here: https://github.com/mirror/boost/blob/master/libs/log/src/process_name.cpp.
On Linux, the filename of your binary is the destination of a symlink at /proc/self/exe. You can use the readlink system call to find the destination of a symlink.
Note that this tells you the actual location on disk where the binary is stored, not simply the command the user used to start your program.
Here's a cross-platform way using boost (https://www.boost.org/)
#include <iostream>
#include <boost/dll.hpp>
int main( int argc, char **argv ) {
std::cout << "hello world, this is [" << boost::dll::program_location().filename().string() << "]" << std::endl;
std::cout << "or [" << boost::dll::program_location().string() << "] if you're not into the whole brevity thing." << std::endl;
return 0;
}
compiled via
g++ -o hello_world hello_world.cpp -lboost_filesystem -lboost_system -ldl
results in the output
hello world, this is [hello_world]
or [/home/gjvc/tmp/hello_world] if you're not into the whole brevity thing.
As others have mentioned, the name of your executable is contained in argv[0]. If you need that, you could:
cout << argv[0] << endl;
If you need the name of a source file of the executable, C++ has a predefined macro you can use:
cout << __FILE__ << endl;
Go to here and scroll to "Predefined macro names"
You can use program_invocation_name from errno.h
https://linux.die.net/man/3/program_invocation_short_name
In Linux (POSIX?) there is an enviroment variable called _ that contains the current process.
$ echo $_
echo
In C++
#include <stdlib.h> /* getenv */
#include<iostream>
int main(){
std::cout << getenv("_") << '\n';
return 0;
}
compile
$ c++ a.cpp -o a.out
$ ./a.out
prints ./a.out (or whatever is the executed line, including path).
This has certain advantages over the other approaches, it can be read globally (not passing argv[0]) and doesn't need file handling.
You can usually get the executable file name from argv[0]:
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("Running: %s\n", argv[0]);
return 0;
}
Indeed, there are ways for an application to execl() another application (or another similar function) and override this argument. It still is unconventional for the system to change it for that sort of application.