Hello
Is there a way to get a pointer to a variable through the variable name
represented as a string?
Let me explain it through an example:
/* Start code example */
int MyVar = 3;
int * MyVarPtr;
MyVarPtr = SomeFunction("MyVar");
/* End code example */
That is, MyVarPtr will be the same as &MyVar
You can do something like that:
#include "symbol_table.h"
#include <stdio.h>
int main(void)
{
declare(int, MyVar);
declare(int*, MyVarPtr);
MyVarPtr = get_symbol("MyVar");
printf("&MyVar = %p\n", (void *) &MyVar);
printf("MyVarPtr = %p\n", (void *) MyVarPtr);
return 0;
}
Where symbol_table.h contains:
#ifndef H_SYMBOL_TABLE
#define H_SYMBOL_TABLE
#include <stddef.h>
struct symbol {
const char *name;
void *pointer;
} *symbol_table;
size_t symbol_table_size;
size_t symbol_table_capacity;
void add_symbol(const char *name, void *pointer);
void *get_symbol(const char *name);
#define declare(type,name) type name; add_symbol(#name, &name);
#endif
And symbol_table.c contains:
#include "symbol_table.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void add_symbol(const char *name, void *pointer)
{
if(!symbol_table_capacity)
{
symbol_table_capacity = 16;
symbol_table = malloc(symbol_table_capacity * sizeof *symbol_table);
}
if(symbol_table_size == symbol_table_capacity)
{
symbol_table_capacity = symbol_table_capacity * 2;
symbol_table = realloc(symbol_table,
symbol_table_capacity * sizeof *symbol_table);
}
if(!symbol_table)
{
fprintf(stderr, "Error allocating memory for symbol table\n");
exit(EXIT_FAILURE);
}
symbol_table[symbol_table_size].name = name;
symbol_table[symbol_table_size].pointer = pointer;
symbol_table_size++;
}
void *get_symbol(const char *name)
{
size_t i;
for(i = 0; i < symbol_table_size; i++)
{
if(!strcmp(symbol_table
.name, name))
return symbol_table.pointer;
}
return NULL;
}