Calling function without signature knowledge [closed]

-1

If I have a function called calculator () in C. And I want to call this function, obviously I would call it by the name, that is, by its signature. But if I do not know the signature of this function, and its signature is in a variable of type char, how could I call this function? that is, get the name of the function stored in the variable of type char, and call the function.

Any suggestions?

Thank you

    
asked by anonymous 12.06.2015 / 15:33

2 answers

2

Rafael,

The C language does not support this type of operation. What you can do is compile a dll with the functions and then search the function by name inside the dll.

Example

#include <Windows.h>
HANDLE funcoes;
int (*teste)(int);

funcoes = LoadLibrary("funcoes.dll");

if(funcoes>(void*)HINSTANCE_ERROR){
      teste = GetProcAddress(funcoes, nomedafuncao);
      teste(5);
} 
    
12.06.2015 / 16:05
1

Tip: show your code. I'll show you my: -)

#include <stdio.h>
#include <string.h>

typedef int (*fx_t)(int); /* fx_t e ponteiro para funcao que recebe e devolve int */

int fx1(int a) { return a + 1; }
int fx2(int a) { return a + 2; }
int fx3(int a) { return a + 3; }

int main(void) {
    char y[10];
    strcpy(y, "fx2"); /* obtem y do utilizador */

    fx_t x = NULL;
    if (strcmp(y, "fx1") == 0) x = fx1;
    if (strcmp(y, "fx2") == 0) x = fx2;
    if (strcmp(y, "fx3") == 0) x = fx3;
    if (x) printf("%d\n", x(42)); // chama fx1(42) ou fx2(42) ou fx3(42) */
    return 0;
}

You can see the code working on ideone .

    
12.06.2015 / 15:50