Generating and running code at run-time, within an application, is quite a well understood problem.
You will be able to find lots of information about generating code, and executing it on the fly, by searching the web for "just in time compiler" or "JIT compilation", "dynamic code generation", especially combined with a programming language name, like 'Java'.
Dynamic code generation is one of the hot research topics of the last fifteen years.
The Java run time system (called the Java Virtual Machine or JVM) uses dynamic compilation technology (called HotSpot) to get dramaticly improved (i.e. > 10x faster) performance.
Microsoft use Just-In-Time compilation for .NET languages like C#, but it will likely be harder to find much detailed information.
Ian Piumarta has been developing some very impressive dynamic compilation technology (e.g. Cola) at Viewpoints Research Institute, working with Alan Kay, the 'father' of SmallTalk (SmallTalk is the starting point for modern Windowing Systems and some types of object orientated programming languages). Some of this technology was used to speed up the Cairo rendering engine (used in web browsers, etc.) in a Google Summer of Code project.
Ian Piumarta's work might be the most flexible, and compact, and hence a good place to start. Be warned, Ian is incredibly clever, so be prepared to really think hard if you want to use it.
There are a few JIT's which generate assembler, which may be exactly what you need (but I have never used them):
Other technologies which might be worth a look include:
- StrongTalk
- Google V8 JavaScript Engine
- LLVM
- GNU libjit
- Intel Open Runtime Platform (ORP)
Of those, LLVM's JIT and GNU libjit are probably the best documented for use outside of their normal 'host' environment. LLVM is technology Apple support. LLVM is designed to be assembled from a set of libraries so that it can be used to build other systems. But it is aimed at very sophisticated, high-performance solutions, so there is likely quite a steep learning curve. GNU libjit looks to be smaller, and hopefully easier to understand because of that. I have only just discovered Intel's ORP.
HTH