views:

225

answers:

9

I know that its possible to read from a .txt file and then convert various parts of that into string, char, and int values, but is it possible to take a string and use it as real code in the program?


Code:

string codeblock1="cout<<This is a test;";
string codeblock2="int array[5]={0,6,6,3,5};}";
int i;
cin>>i;
if(i)
{
execute(codeblock1);
}
else
{
execute(codeblock2);
}

Where execute is a function that converts from text to actual code (I don't know if there actually is a function called execute, I'm using it for the purpose of my example).

+3  A: 

You can create a function and parse whatever strings you like and create a data structure from it. This is known as a parse tree. Subsequently you can examine your parse tree and generate the necessary dynamic structures to perform the logic therin. The parse tree is subsequently converted into a runtime representation that is executed.

All compilers do exactly this. They take your code and they produce machine code based on this. In your particular case you want a language to write code for itself. Normally this is done in the context of a code generator and it is part of a larger build process. If you write a program to parse your language (consider flex and bison for this operation) that generates code you can achieve the results you desire.

ojblass
A: 

Yes, you just have to build a compiler (and possibly a linker) and you're there.

Several languages such as Python can be embedded into C/C++ so that may be an option.

Brian Rasmussen
A: 

It's kind of sort of possible, but not with just straight C/C++. You'll need some layer underneath such as LLVM.

Check out c-repl and ccons

Brian Gianforcaro
A: 

One way that you could do this is with Boost Python. You wouldn't be using C++ at that point, but it's a good way of allowing the user to use a scripting language to interact with the existing program. I know it's not exactly what you want, but perhaps it might help.

sharth
+8  A: 

In C++ there's no simple way to do this. This feature is available in higher-level languages like Python, Lisp, Ruby and Perl (usually with some variation of an eval function). However, even in these languages this practice is frowned upon, because it can result in very unreadable code.

It's important you ask yourself (and perhaps tell us) why you want to do it?

Or do you only want to know if it's possible? If so, it is, though in a hairy way. You can write a C++ source file (generate whatever you want into it, as long as it's valid C++), then compile it and link to your code. All of this can be done automatically, of course, as long as a compiler is available to you in runtime (and you just execute it with system). I know someone who did this for some heavy optimization once. It's not pretty, but can be made to work.

Eli Bendersky
A: 

Sounds like you're trying to create "C++Script", which doesn't exist as far as I know. C++ is a compiled language. This means it always must be compiled to native bytecode before being executed. You could wrap the code as a function, run it through a compiler, then execute the resulting DLL dynamically, but you're not going to get access to anything a compiled DLL wouldn't normally get.

You'd be better off trying to do this in Java, JavaScript, VBScript, or .NET, which are at one stage or another interpreted languages. Most of these languages either have an eval or execute function for just that, or can just be included as text.

Of course executing blocks of code isn't the safest idea - it will leave you vulnerable to all kinds of data execution attacks.

My recommendation would be to create a scripting language that serves the purposes of your application. This would give the user a limited set of instructions for security reasons, and allow you to interact with the existing program much more dynamically than a compiled external block.

lc
There is absolutely nothing in the C++ spec that requires compilation. It was designed to be a compiled language, and is (as far as I know) always implemented as such. Similarly, Java is as much a compiled language as C++, even if the target platform is prespecified. Not to mention that compiled vs. interpreted doesn't mean not having or having some sort of eval: Common Lisp is usually a compiled language with (eval ... ), while I've used interpreted languages without.
David Thornley
+2  A: 

Many scripting languages offer this sort of feature, going all the way back to eval in LISP - but C and C++ don't expose the compiler at runtime.

There's nothing in the spec that stops you from creating and executing some arbitrary machine language, like so:

char code[] = { 0x2f, 0x3c, 0x17, 0x43 }; // some machine code of some sort
typedef void (FuncType*)();               // define a function pointer type
FuncType func = (FuncType)code;           // take the address of the code
func();                                   // and jump to it!

but most environments will crash if you try this, for security reasons. (Many viruses work by convincing ordinary programs to do something like this.)

In a normal environment, one thing you could do is create a complete program as text, then invoke the compiler to compile it and invoke the resulting executable.

If you want to run code in your own memory space, you could invoke the compiler to build you a DLL (or .so, depending on your platform) and then link in the DLL and jump into it.

Charlie Tangora
In fact many platforms *won't* crash if you do this; there was once a project called SoftWire that did exactly this (it let you write 'pixel shaders' in C for a software renderer, if I remember correctly). I ended up rewriting a clone of that project after it disappeared as a JIT compiler for a toy programming language. It's fun, but dangerous... do it!
Zach Snow
Yes, there are many platforms on which it runs, but sadly OS and hardware designers seem to be trending towards locking down "non-executable" data. I know of some PS2 games that did truly wild and wonderful things with this sort of technique... happily, "code is data is code" lives on in the PS3 SPUs, which have no memory protection at all!
Charlie Tangora
+1  A: 

First, I wanted to say, that I never implemented something like that myself and I may be way off, however, did you try CodeDomProvider class in System.CodeDom.Compiler namespace? I have a feeling the classes in System.CodeDom can provide you with the functionality you are looking for.

Of course, it will all be .NET code, not any other platform

Go here for sample

galets
A: 

Not easily, because C++ is a compiled language. Several people have pointed round-about ways to make it work - either execute the compiler, or incorporate a compiler or interpreter into your program. If you want to go the interpreter route, you can save yourself a lot of work by using an existing open source project, such as Lua

Justin Love