Re: Mapping parsed function info to a c call
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Thu, 28 May 2009 13:37:57 +0100
nick_keighley_nospam@xxxxxxxxxxx writes:
[I am replying to your message (rather than to the OP) because it
contains a good summary of the problem.]
On 28 May, 09:30, niq <zed...@xxxxxxxxx> wrote:<snip>
On 2009-05-28, nick_keighley_nos...@xxxxxxxxxxx
<nick_keighley_nos...@xxxxxxxxxxx> wrote:
please include the full context in the body of your message.
i'm writing a simple interpreter with c-like language
so input -> parser -> ast -> engine -> output(or some action)
there are a lot of funcs so it is silly (i thought) to implement a sin
function when we have it in standard c libs.
quite right. Implementing the full c math library would be quite an
undertaking.
so you essentially want to map function name to function
call.
the "difficulty" with function pointers is you must call the
function through the correct function pointer.
consider
int f1 (int i) {};
int f2 (int i, int j) {};
and you want to store them in a "generic" function pointer
Fptr fa[] = {(Fptr)f1, (Fptr)f2};
(I haven't tested this so it may not be exactly right).
Thats ok. But at some point you want to call f2
fa[1]();
all hell breaks loose as f2 is expecting two parameters.
So have to carefully cast the generic FP back to the right
type and pass it the right parameters. If the is huge variety
in the types of your functions you may be better with the Giant
Switch (or at least consider for a first hack).
Another strategy is to define a type that works for all your functions
and write small wrappers for all the standard functions:
typedef union { double dval; ... } Value;
typedef Value function(int n_args, Value *args);
Value my_sin(int n_args, Value *args)
{
return (Value){ .dval = sin(args[0].dval) };
}
I'm using C99 features hear because the simplify such things. The
wrappers the go in the table and are all called though the same
correct pointer type (I prefer to define function types rather pointer
to function types, but that is a detail).
Coding out loud here
Ditto.
<snip>
--
Ben.
.
- References:
- Mapping parsed function info to a c call
- From: niq
- Re: Mapping parsed function info to a c call
- From: nick_keighley_nospam
- Re: Mapping parsed function info to a c call
- From: niq
- Re: Mapping parsed function info to a c call
- From: nick_keighley_nospam
- Mapping parsed function info to a c call
- Prev by Date: Re: A Queue implementation of doubly linked list in C
- Next by Date: Re: A Queue implementation of doubly linked list in C
- Previous by thread: Re: Mapping parsed function info to a c call
- Next by thread: Re: Mapping parsed function info to a c call
- Index(es):
Relevant Pages
|