Le 22/08/12 17:05, James Kuyper a écrit :
If you have the JIT of lcc-win you write:
typedef int (*foo)(int);
foo adder_factory(int value)
{
foo fnPtr;
char buf[512];
sprintf(buf,"int fn(int a) { return a + %d;}",value);
fnPtr = (foo)compile(buf);
return fnPtr;
You could accomplish similiar [though more longwinded] via compiling
code and using dlopen() to load it into your process space.
The intent was for the definition of the adder to be contained inside
the definition of adder_factory().
Both of which are completely OT for this group though.
BTW: your code doesn't seem to do any sort of error checking. What if
compile() fails?
From the way it's used, it would appear to return a pointer.
By convention it returns a pointer to the first function it finds.
This is highly dependent on the application and customer setup.
Some customers want to have a "main" function that starts the thing.
In that case the JIT will return a pointer to that function. Others
will put the main function at the start of the file and the Jit returns
a function to the first function it compiles.
In case of error (syntax error, no more memory, whatever catastrophe
occurs), it returns NULL. Diagnostics are printed in stderr, whatever
that is. In most applications stderr is a pipe connected to some
file.
Obviously in most applications the code buffer is machine generated.
It could be however that it is used as a C interpreter.
The resulting code is dynamically linked to the running program. There
is no preprocessor.
If
compile() fails, it might return a null pointer, in which case
adder_factory() will also return a null pointer, leaving it for the
caller to decide what to do about it. That's a perfectly reasonable way
of passing on the information that the call failed.
However, I think that compile() looks horribly type-unsafe.
In a sense yes, since it can return a pointer to ANY kind of function
by definition... It is up to you to cast the result pointer into
the right stuff. I do not see how to improve that without destroying
the generality of the program.
But we are used to it. fread() will read ANY kind of stuff into its
buffer, it is up to you to interpret the data correctly.