For Programmers: Free Programming Magazines  


Home > Archive > Unix Programming > August 2006 > generated functions









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author generated functions
shaanxxx

2006-08-26, 7:59 am

I want to write a programme. I explain what it does.
1) It generates C code . // i know how to do it
2) It compiles that generated code. // i know how to do it.

IMPORTANT ONE :
3) Now It calls one of the functions in generated code. // need help on
this.

I need guidance in third point.


Thanks
Shaan

Rainer Temme

2006-08-26, 7:59 am

shaanxxx wrote:
> I want to write a programme. I explain what it does.
> 1) It generates C code . // i know how to do it
> 2) It compiles that generated code. // i know how to do it.
>
> IMPORTANT ONE :
> 3) Now It calls one of the functions in generated code. // need help on
> this.


Ok, I assume you'll get (1) donbe by yourself, since only you
know, what the functions shall do ...

(2) generate the code from the c-file into a shared-library.

(3) Use dlopen() dlsym() to open/load the
shared library and to obtain functionpointers, and call
the functions via the pointers.

Done.

Rainer
jmcgill

2006-08-29, 4:11 am

shaanxxx wrote:
> I want to write a programme. I explain what it does.
> 1) It generates C code . // i know how to do it
> 2) It compiles that generated code. // i know how to do it.
>
> IMPORTANT ONE :
> 3) Now It calls one of the functions in generated code. // need help on
> this.
>
> I need guidance in third point.


If you can prototype your function your other code can work in terms of
a pointer to that function, that is, you can make a call to a function
by reference, without knowing at compile time what actual function will
be referenced. There's lots of UI code that works on that principle,
and even entire languages based on the idea of dynamic function binding.
This is the canonical way to implement callbacks in C, like when you
want to specify a comparison function to a sort routine, so that you
don't have to specialize such a routine to a certain type.

Runtime function binding isn't really more difficult than, say, pointers
to structs.

This initializes a pointer to a function:

int f( int ); // prototype -- important
int (*pf)( int ) = &f; // initialized a pointer to function f

then you can call the function like:

int ret;

ret = (*pf)( 0 ); // calls function f -- there are other ways to call it.

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com