Passing function pointers & int references to another function - c

Just started working on a c project. Need help with passing function pointers/macro functions/etc. I'm a php & python OO guy, but new to c. I tried to generalize the example for this post. I have a main.c with a lib for the Axon microcontroller I'm working with. Works like a charm with everything in main.c. I need to move some of the functionality out of main to more organized lib files as my code grows. The base microcontroller lib creates a macro function that allows me to send data to the microcontroller to make a servo move left or right. I now need to create a servo specific file (HS-422.c) that will will allow me to pass references/pointers(?) to a generic function that will execute for each servo to ease on code duplication.
Keep in mind I'm only focused on passing macros/functions/variable references to other functions and have them called / set. The other basics of c I understand. I must have tried a 100 different ways to make this work today with no luck. So just wrote a simplified version hoping you might get an idea of what I'm attempting.
Thank you for your help!
/*
* main.h
* I'm trying to make a pointer or reference to the macro.
* The original file had:
* #define servo1(position) servo(PORTE,2,position);
*/
// servo is a macro defined in another microcontroller file
#define (void)(*servo1)(position) servo(PORTE,2,position);
#define (void)(*servo2)(position) servo(PORTE,3,position);
/* main.c */
// init main functions
void servo_scan(void);
// init vars
int servo1_location = 0;
int servo2_location = 0;
int main(void)
{
for(;;)
{
servo_turn();
}
}
// get the servos to turn
void servo_turn(void)
{
turn_servo( *servo1, &servo1_location, 200);
turn_servo( *servo2, &servo2_location, 950);
}
/* HS-422.c */
void turn_servo(void (*servo)(int position), int &currentLocation, int newLocation)
{
// turning
for(uint16_t i=&currentLocation; i<newLocation; i=i+10)
{
// turn servo
// hoping the specifc passed servo# pointer gets called
*servo(i);
// set value by reference to origional servo#_location var. making sure.
&currentLocation = i;
// pause
delay_ms(20);
}
}

It's not really clear to me exactly what you're trying to achieve, but what is clear is that you don't really understand the concept of pointers/references in C - so I'll try to clarify, and hopefully that will help you implement what you need.
Firstly, there is no such thing as a "reference" in C. The only alternative to passing by value is to pass a pointer. A pointer is basically just a memory address, and you can get a pointer (memory address) to a variable using the & (address of) operator. When passing a pointer variable to a function, you do something like the following:
Given a function which takes a pointer:
int foo(int* pointer);
You would pass the memory address of an int variable to this function like so:
int x = 10;
foo(&x);
So right off the bat, you can see that your function definition above is wrong:
void turn_servo(void (*servo)(int position), int &currentLocation, int newLocation);
This is simply a syntax error. It will not compile because of the int &currentLocation. The & operator is used to take the address of a variable. It can't be used in a function parameter. If you want a "reference" to currentLocation, you need to pass in a pointer, so your function parameters should be written as:
void turn_servo(void (*servo)(int position), int* currentLocation, int newLocation);
Secondly, when you want to modify the value pointed to by the currentLocation pointer, you need to use the * operator to dereference the pointer. So, the line where you set currentLocation is not correct. What you want to say is:
// set value by to origional servo#_location var. making sure.
*currentLocation = i;
And of course, the line:
for(uint16_t i=&currentLocation; i<newLocation; i=i+10)
should be:
for(uint16_t i= *currentLocation; i<newLocation; i=i+10)
Note that in your original code you use the & operator in both cases, which takes the address of a variable. Since currentLocation is already a memory address, this would result in taking the address of an address, also known as a pointer-to-a-pointer, which is certainly not what you want here.
Finally, the phrase "pointer or reference to the macro" is completely nonsensical. A macro is not a function. It is more like a meta-function: essentially it is a template used by the C preprocessor to generate further source code. The C preprocessor is invoked before the compilation phase, and basically acts as a find/replace mechanism in the source code. You can't have a pointer to a macro, because for all intents and purposes macros don't even exist in the compilation phase. They are only meaningful to the preprocessor.
There may be more here, but ultimately you seem to have a fundamental misunderstanding of pointers (as well as macros) in C, and short of providing a complete tutorial, the best I can do is point out the syntax problems. I highly recommend you read a good introductory book to C, which will certainly go over pointers, macros, and functions.

I have picked the main point of your code and have this code below.
You may want to modify your #define in your original code.
Please see the code below: (you can also run this)
void myFunc(int pos);
void myFunc2(int pos);
int main (int argc, const char * argv[]) {
typedef void (*pFunc)(int);
pFunc pfArr[2];
pfArr[0] = &myFunc;
pfArr[1] = &myFunc2;
int x = 3;
int newLoc = 4;
turn_servo(pfArr[1], x, newLoc);
turn_servo(pfArr[0], x, newLoc);
return 0;
}
void turn_servo(void (*servo)(int position), int currentLocation, int newLocation)
{
printf("\nturn_servo starts");
printf("\nturn_servo currentLocation: %d", currentLocation);
printf("\nturn_servo newLocation: %d", newLocation);
servo(1);
}
void myFunc(int pos)
{
printf("\nmyFunc starts");
printf("\nmyFunc pos: %d", pos);
}
void myFunc2(int pos)
{
printf("\nmyFunc2 starts");
printf("\nmyFunc2 pos: %d", pos);
}
Your turn_servo() function will now accept two functions as parameter (either myFunc() or myFunc2()).
Just get the main point of this code and apply it. Hope this will help.

Related

How to obtain the function name and number of arguments from a function in C?

Lets say I am maintaining an array of function structures in which I store API information.
This is definition of function structure:
typedef struct function {
void (*func)(long, ...);
char* name;
int argc;
char *argv[];
} function;
function api_list[N]
I would maintain a list of such structures.
Now given any function, I want to write a function Register(api_list, fp)
which adds one such structure initialized with details of function fp.
int fp(int a, int b) {
return a+b;
}
Register(api_list, fp);
How to do it in C?
I believe you will need to either parse the C function declarations yourself or find some other code to do it. I looked around a bit and there's code for this in the Ruby FFI, PerlXS and other script binding generators like SWIG. I also saw the XML plugin to GCC which generates XML describing the program.
If you look up C's BNF or EBNF definitions and know a bit of parsing theory, figuring out C functions is not hard. C++ is a whole other ball o' wax.
Note: I think I misunderstood. The following is for calling C functions with unknown number and types of arguments. Not for finding out what the function signature already looks like.
Look at the FFI (Foreign Function Interface) library which can be found at Sourceware:
https://sourceware.org/libffi/
This is packaged with many Linux systems already because it is heavily used by interpreted languages that need to call C functions.
Now given any function, I want to write a function Register(api_list, fp) which adds one such structure initialized with details of function fp.
There is no way to do this in Standard C. The main reason is you need keep track of original definition of an function to call it via such structure. You actually could store every function pointer as struct member:
void (*func)()
that is fine, but any attempt to call such function when type is not compatible (both parameters and return type are not the same) with original definition will invoke undefined behaviour. This means, that you would need to cast it properly for every call:
((int (*)(int, int)) api_list[0])(1, 2);
You may use GCC extensions typeof, but this method requires writing function's name (here fp) explicitely:
int result = ( (typeof(fp)*) api_list[0].func)(1, 2);
Even if you have stored somehow character string "fp" inside name member, there is no way to "connect" it with typeof, since it does not take string literals (well it takes, but not in the way you want) and in general there is no way to have it "destringized" as fp token.
Here is an illustration of above concepts:
#include <stdio.h>
typedef void (*GENERIC_FUNC_PTR)();
typedef struct function
{
GENERIC_FUNC_PTR func;
} function;
void Register(function *api_list, GENERIC_FUNC_PTR func)
{
api_list->func = func;
}
int add(int a, int b)
{
return a + b;
}
void print_message(void)
{
printf("%s\n", __func__);
}
int main(void)
{
function api_list[10];
Register(api_list, (GENERIC_FUNC_PTR) add);
Register(api_list + 1, (GENERIC_FUNC_PTR) print_message);
printf("%d\n", ( (typeof(add)*) api_list[0].func)(1, 2));
( (typeof(print_message)*) api_list[1].func)();
return 0;
}

Call flow for the code - C

I am looking into some C code for a microcontroller. I understand most of the code however this piece of the code is puzzling me.
I am also including relevant definitions for used data types. I have substituted function and variable names for the ease sake.
#define COUNT (2)
typedef void(*some_type)(void *p);
some_type some_arr[COUNT] = {NULL, };
void init(void)
{
first_function(&second_function);
}
void first_function(some_type cb)
{
if(some_arr_count < COUNT)
{
some_arr[some_arr_count++] = cb;
}
}
void second_function(void *p)
{
another_type *req;
req = (another_type *)p;
//some other code goes here
}
1.What does this typedef means?
typedef void(*some_type)(void *p);
init() function gets called only once and it has only one line of code.
2.What does this line do?
first_function(&second_function);
I searched for the term second_function in the entire project code and it this the only place it appears besides function definition.
3.So how does second_function get called?
The following typedef
typedef void(*some_type)(void *p);
will define some_type as a pointer to function of type void ()(void *).
The following statement
first_function(&second_function);
is a function call, &second_function, which is the address of second_function , is the argument to first_function().
The function second_function could be called like this
some_arr[some_arr_count](p);
some_arr[some_arr_count] is a function pointer to second_function, which is assigned in first_function, and p is the argument of second_function, which is a pointer to void.
Firstly, as suggested in the comments you should go read about function pointers. I got this (How do function pointers in C work?) from a Google search.
The above link should help to explain answers to question 1 and 2. For question 3, it is likely that the micro-controller has some built-in mechanism or library function which calls all the function call-backs in some_arr[COUNT], something like the following might work (untested):
for (int i = 0; i < COUNT; ++i)
{
if (some_arr[i] == NULL) break;
(*some_arr[i])(&something_useful);
}
Where something_useful would be some sort of data that the call-back function could use.
If you are able to search the library code for uses of some_arr you might find code to call the second_function (although it will no longer be called second_function).

How to send a lot of variables to a generic function?

I have a function f, defined as following:
struct s {
void *data;
struct s *next;
};
void
f(struct s **p, void *q)
{
/* ... */
}
void *
g(struct s **p)
{
/* ... */
}
I have to test these functions, using a lot of different arguments. But pointers to void can contain only an object address, right ? So how can I automate operations as following, without using temporary variable (or maybe in a macro).
f(p, 2);
f(p, 'c');
f(p, 3.14);
There's no way around of a temporary variable (well, you can use a static variable, it sure isn't temporary!) because you need an address, thus you need a (non-register) variable.
However, that doesn't mean you need additinal lines of code: you can use a typed initializer (as of C99):
f(p, &(int){2});
f(p, &(double){3.14});
However, the function (as you have defined it) has no way of knowing how big an object you have just passed to it, and it must not just store the pointer value because it's a pointer to a very temporary variable.
(Integers can be converted to pointers and back again with some restrictions but you have to check your implementation for details.)
Make an array of the test variables and make a for loop to call it on by one. That way you will be able to send the address directly maybe something like that should work:
for (int i = 0; i < NumOfTestCases; i++)
{
f(p, &pArrOfTestCases[i]);
}
I hope that helps.
You can look at this thread example which accepts arguments similar way:
_beginthread( Bounce, 0, (void *) (structure_of_whatever_variables) );
^
|
|
This is the parameter of function Bounce
This is source of above example.

Trying to understand function pointers in C

I am trying to understand function pointers and am stuggling. I have seen the sorting example in K&R and a few other similar examples. My main problem is with what the computer is actually doing. I created a very simple program to try to see the basics. Please see the following:
#include <stdio.h>
int func0(int*,int*);
int func1(int*,int*);
int main(){
int i = 1;
myfunc(34,23,(int(*)(void*,void*))(i==1?func0:func1));//34 and 23 are arbitrary inputs
}
void myfunc(int x, int y, int(*somefunc)(void *, void *)){
int *xx =&x;
int *yy=&y;
printf("%i",somefunc(xx,yy));
}
int func0(int *x, int *y){
return (*x)*(*y);
}
int func1(int *x, int *y){
return *x+*y;
}
The program either multiplies or adds two numbers depending on some variable (i in the main function - should probably be an argument in the main). fun0 multiplies two ints and func1 adds them.
I know that this example is simple but how is passing a function pointer preferrable to putting a conditional inside the function myfunc?
i.e. in myfunc have the following:
if(i == 1)printf("%i",func0(xx,yy));
else printf("%i",func1(xx,yy));
If I did this the result would be the same but without the use of function pointers.
Your understanding of how function pointers work is just fine. What you're not seeing is how a software system will benefit from using function pointers. They become important when working with components that are not aware of the others.
qsort() is a good example. qsort will let you sort any array and is not actually aware of what makes up the array. So if you have an array of structs, or more likely pointers to structs, you would have to provide a function that could compare the structs.
struct foo {
char * name;
int magnitude;
int something;
};
int cmp_foo(const void *_p1, const void *_p2)
{
p1 = (struct foo*)_p1;
p2 = (struct foo*)_p2;
return p1->magnitude - p2->magnitude;
}
struct foo ** foos;
// init 10 foo structures...
qsort(foos, 10, sizeof(foo *), cmp_foo);
Then the foos array will be sorted based on the magnitude field.
As you can see, this allows you to use qsort for any type -- you only have to provide the comparison function.
Another common usage of function pointers are callbacks, for example in GUI programming. If you want a function to be called when a button is clicked, you would provide a function pointer to the GUI library when setting up the button.
how is passing a function pointer preferrable to putting a conditional inside the function myfunc
Sometimes it is impossible to put a condition there: for example, if you are writing a sorting algorithm, and you do not know what you are sorting ahead of time, you simply cannot put a conditional; function pointer lets you "plug in" a piece of computation into the main algorithm without jumping through hoops.
As far as how the mechanism works, the idea is simple: all your compiled code is located in the program memory, and the CPU executes it starting at a certain address. There are instructions to make CPU jump between addresses, remember the current address and jump, recall the address of a prior jump and go back to it, and so on. When you call a function, one of the things the CPU needs to know is its address in the program memory. The name of the function represents that address. You can supply that address directly, or you can assign it to a pointer for indirect access. This is similar to accessing values through a pointer, except in this case you access the code indirectly, instead of accessing the data.
First of all, you can never typecast a function pointer into a function pointer of a different type. That is undefined behavior in C (C11 6.5.2.2).
A very important advise when dealing with function pointers is to always use typedefs.
So, your code could/should be rewritten as:
typedef int (*func_t)(int*, int*);
int func0(int*,int*);
int func1(int*,int*);
int main(){
int i = 1;
myfunc(34,23, (i==1?func0:func1)); //34 and 23 are arbitrary inputs
}
void myfunc(int x, int y, func_t func){
To answer the question, you want to use function pointers as parameters when you don't know the nature of the function. This is common when writing generic algorithms.
Take the standard C function bsearch() as an example:
void *bsearch (const void *key,
const void *base,
size_t nmemb,
size_t size,
int (*compar)(const void *, const void *));
);
This is a generic binary search algorithm, searching through any form of one-dimensional arrray, containing unknown types of data, such as user-defined types. Here, the "compar" function is comparing two objects of unknown nature for equality, returning a number to indicate this.
"The function shall return an integer less than, equal to, or greater than zero if the key object is considered, respectively, to be less than, to match, or to be greater than the array element."
The function is written by the caller, who knows the nature of the data. In computer science, this is called a "function object" or sometimes "functor". It is commonly encountered in object-oriented design.
An example (pseudo code):
typedef struct // some user-defined type
{
int* ptr;
int x;
int y;
} Something_t;
int compare_Something_t (const void* p1, const void* p2)
{
const Something_t* s1 = (const Something_t*)p1;
const Something_t* s2 = (const Something_t*)p2;
return s1->y - s2->y; // some user-defined comparison relevant to the object
}
...
Something_t search_key = { ... };
Something_t array[] = { ... };
Something_t* result;
result = bsearch(&search_key,
array,
sizeof(array) / sizeof(Something_t), // number of objects
sizeof(Something_t), // size of one object
compare_Something_t // function object
);

Dynamically creating functions in C

How can I dynamically create a function in C?
I try to summarize my C problem as follows:
I have a matrix and I want to be able to use some function to generate its elements.
function has no arguments
Hence I define the following:
typedef double(function)(unsigned int,unsigned int);
/* writes f(x,y) to each element x,y of the matrix*/
void apply(double ** matrix, function * f);
Now I need to generate constant functions within the code. I thought about creating a nested function and returning its pointer, but GCC manual (which allows nested functions) says:
"If you try to call the nested function through its address after the
containing function has exited, all hell will break loose."
which I would kind of expect from this code...
function * createConstantFunction(const double value){
double function(unsigned int,unsigned int){
return value;
}
return &function;
}
So how can I get it to work?
Thanks!
C is a compiled language. You can't create code at run-time "in C"; there is no specific C support to emit instructions to memory and so on. You can of course try just allocating memory, making sure it's executable, and emit raw machine code there. Then call it from C using a suitable function pointer.
You won't get any help from the language itself though, this is just like generating code and calling it in BASIC on an old 8-bit machine.
You must be familiar with some programming language which supports closure mechanism ,don't you?
Unfortunately, C does not support closure like that itself.
You could find out some useful libraries which simulate closure in C if you insisted on closure. But most of those libraries are complex and machine-dependence.
Alternatively, you can change your mind to agree with the C-style closure if you could change the signature of double ()(unsigned,unsigned);.
In C, functions itself has no data (or context) except the parameters of it and the static variable which it could access.
So the context must be passed by yourself. Here is a example using extra parameter :
// first, add one extra parameter in the signature of function.
typedef double(function)(double extra, unsigned int,unsigned int);
// second, add one extra parameter in the signature of apply
void apply(double* matrix,unsigned width,unsigned height, function* f, double extra)
{
for (unsigned y=0; y< height; ++y)
for (unsigned x=0; x< width ++x)
matrix[ y*width + x ] = f(x, y, extra);
// apply will passing extra to f
}
// third, in constant_function, we could get the context: double extra, and return it
double constant_function(double value, unsigned x,unsigned y) { return value; }
void test(void)
{
double* matrix = get_a_matrix();
// fourth, passing the extra parameter to apply
apply(matrix, w, h, &constant_function, 1212.0);
// the matrix will be filled with 1212.0
}
Is a double extra enough? Yes, but only in this case.
How should we do if more context is required?
In C, the general purpose parameter is void*, we can pass any context though one void* parameter by passing the address of context.
Here is another example :
typedef double (function)(void* context, int, int );
void apply(double* matrix, int width,int height,function* f,void* context)
{
for (int y=0; y< height; ++y)
for (int x=0; x< width ++x)
matrix[ y*width + x ] = f(x, y, context); // passing the context
}
double constant_function(void* context,int x,int y)
{
// this function use an extra double parameter \
// and context points to its address
double* d = context;
return *d;
}
void test(void)
{
double* matrix = get_a_matrix();
double context = 326.0;
// fill matrix with 326.0
apply( matrix, w, h, &constant_function, &context);
}
(function,context) pair like &constant_function,&context is the C-style closure.
Each function(F) that needs a closure must has one context parameter which will be passed to closure as its context.
And the caller of F must use a correct (f,c) pair.
If you can change the signature of function to fit to C-style closure, your code will be simple and machine-independence.
If couldn't (function and apply is not written by you), try to persuade him to change his code.
If failed, you have no choice but to use some closure libraries.
Since you want to generate a function that follows a simple recipe,
this shouldn't be too tricky to do with some inline assembly and
a block of executable/writable memory.
This approach feels a bit hacky so I wouldn't recommend it in production code. Due to the use of inline assembly this solution works only on Intel x86-64 / AMD64, and will need to be translated to work with other architectures.
You might prefer this to other JIT-based solutions as it does not depend on any external library.
If you would like a longer explanation of how the below code works,
leave a comment and I'll add it.
For security reasons, the code page should be marked PROT_READ|PROT_EXEC after a function is generated (see mprotect).
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/mman.h>
int snippet_processor(char *buffer, double value, int action);
enum snippet_actions {
S_CALC_SIZE,
S_COPY,
};
typedef double (*callback_t) (unsigned int, unsigned int);
int main(int argc, char **argv) {
unsigned int pagesize = 4096;
char *codepage = 0;
int snipsz = 0;
callback_t f;
/* allocate some readable, writable and executable memory */
codepage = mmap(codepage,
pagesize,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_ANONYMOUS | MAP_PRIVATE,
0,
0);
// generate one function at `codepage` and call it
snipsz += snippet_processor(codepage, 12.55, S_COPY);
f = (callback_t) (codepage);
printf("result :: %f\n", f(1, 2));
/* ensure the next code address is byte aligned
* - add 7 bits to ensure an overflow to the next byte.
* If it doesn't overflow then it was already byte aligned.
* - Next, throw away any of the "extra" bit from the overflow,
* by using the negative of the alignment value
* (see how 2's complement works.
*/
codepage += (snipsz + 7) & -8;
// generate another function at `codepage` and call it
snipsz += snippet_processor(codepage, 16.1234, S_COPY);
f = (callback_t) (codepage);
printf("result :: %f\n", f(1, 2));
}
int snippet_processor(char *buffer, double value, int action) {
static void *snip_start = NULL;
static void *snip_end = NULL;
static void *double_start = NULL;
static int double_offset_start = 0;
static int size;
char *i, *j;
int sz;
char *func_start;
func_start = buffer;
if (snip_start == NULL) {
asm volatile(
// Don't actually execute the dynamic code snippet upon entry
"jmp .snippet_end\n"
/* BEGIN snippet */
".snippet_begin:\n"
"movq .value_start(%%rip), %%rax\n"
"movd %%rax, %%xmm0\n"
"ret\n"
/* this is where we store the value returned by this function */
".value_start:\n"
".double 1.34\n"
".snippet_end:\n"
/* END snippet */
"leaq .snippet_begin(%%rip), %0\n"
"leaq .snippet_end(%%rip), %1\n"
"leaq .value_start(%%rip), %2\n"
:
"=r"(snip_start),
"=r"(snip_end),
"=r"(double_start)
);
double_offset_start = (double_start - snip_start);
size = (snip_end - snip_start);
}
if (action == S_COPY) {
/* copy the snippet value */
i = snip_start;
while (i != snip_end) *(buffer++) = *(i++);
/* copy the float value */
sz = sizeof(double);
i = func_start + double_offset_start;
j = (char *) &value;
while (sz--) *(i++) = *(j++);
}
return size;
}
Using FFCALL, which handles the platform-specific trickery to make this work:
#include <stdio.h>
#include <stdarg.h>
#include <callback.h>
static double internalDoubleFunction(const double value, ...) {
return value;
}
double (*constDoubleFunction(const double value))() {
return alloc_callback(&internalDoubleFunction, value);
}
main() {
double (*fn)(unsigned int, unsigned int) = constDoubleFunction(5.0);
printf("%g\n", (*fn)(3, 4));
free_callback(fn);
return 0;
}
(Untested since I don't have FFCALL currently installed, but I remember that it works something like this.)
One way of doing would be to write a standard C file with the set of functions you want, compile it via gcc and the load it as a dynamic library to get pointers to the functions.
Ultimately, it probably would be better if you were able to specify your functions without having to define them on-the-fly (like via having a generic template function that takes arguments that define its specific behavior).
If you want to write code on the fly for execution, nanojit might be a good way to go.
In your code above, you're trying to create a closure. C doesn't support that. There are some heinous ways to fake it, but out of the box you're not going to be able to runtime bind a variable into your function.
As unwind already mentioned, "creating code at runtime" is not supported by the language and will be a lot of work.
I haven't used it myself, but one of my co-workers swears by Lua, an "embedded language". There is a Lua C API which will (theoretically, at least) allow you to perform dynamic (scripted) operations.
Of course, the downside would be that the end user may need some sort of training in Lua.
It may be a dumb question, but why does the function have to be generated within your application? Similarly what advantage does the end-user get from generating the function themselves (as opposed to selecting from one or more predefined functions that you provide)?
This mechanism is called reflection where code modifies its own behavior at runtime. Java supports reflection api to do this job.
But I think this support is not available in C.
Sun web site says :
Reflection is powerful, but should not
be used indiscriminately. If it is
possible to perform an operation
without using reflection, then it is
preferable to avoid using it. The
following concerns should be kept in
mind when accessing code via
reflection.
Drawbacks of Reflection
Performance Overhead Because
reflection involves types that are
dynamically resolved, certain Java
virtual machine optimizations can not
be performed. Consequently, reflective
operations have slower performance
than their non-reflective
counterparts, and should be avoided in
sections of code which are called
frequently in performance-sensitive
applications.
Security Restrictions
Reflection requires a runtime
permission which may not be present
when running under a security manager.
This is in an important consideration
for code which has to run in a
restricted security context, such as
in an Applet.
Exposure of Internals
Since reflection allows code to
perform operations that would be
illegal in non-reflective code, such
as accessing private fields and
methods, the use of reflection can
result in unexpected side-effects,
which may render code dysfunctional
and may destroy portability.
Reflective code breaks abstractions
and therefore may change behavior with
upgrades of the platform. .
It looks like you're coming from another language where you commonly use this type of code. C doesn't support it and it although you could certainly cook up something to dynamically generate code, it is very likely that this isn't worth the effort.
What you need to do instead is add an extra parameter to the function that references the matrix it is supposed to work on. This is most likely what a language supporting dynamic functions would do internally anyway.
If you really need to dynamically create the functions, maybe an embedded C interpreter could help. I've just googled for "embedded C interpreter" and got Ch as a result:
http://www.softintegration.com/
Never heard of it, so I don't know anything about it, but it seems to be worth a look.

Resources