Skip to content

Instantly share code, notes, and snippets.

@mrtrizer
Last active October 5, 2021 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtrizer/45823efc83d7aa4acc2a045266abdfcf to your computer and use it in GitHub Desktop.
Save mrtrizer/45823efc83d7aa4acc2a045266abdfcf to your computer and use it in GitHub Desktop.
Basic 10 lines type reflection implementation in C (see another gist if you need reflection for functions)
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
// Lib code
char* ___tid(const char* strPtr) { return (char*)strPtr; }
#define TID(type) ((intptr_t)___tid(#type))
#define FIELD(type, field, fieldType) operation->operation(operation->context, operation->data + offsetof(type, field), #field, TID(fieldType))
typedef struct
{
void* data;
void* context;
void (*operation)(void*, void*, const char*, intptr_t);
} Operation;
// Usage
typedef struct
{
int i;
int j;
} Test;
void Test_ref(Operation* operation)
{
FIELD(Test, i, int);
FIELD(Test, j, int);
}
void int_ref(Operation* operation)
{
// ImGUI / Serialization / Desirialization here
printf("%d\n", *(int*)operation->data);
}
void toStr(void* context, void* val, const char* name, intptr_t typeId)
{
Operation operation = { .data = val, .operation = toStr, .context = context };
// Use dictionary here, put dictionary to context
if (typeId == TID(int))
{
printf("%s = ", name);
int_ref(&operation);
}
if (typeId == TID(Test))
{
printf("Test\n");
Test_ref(&operation);
}
}
int main(void)
{
Test test = { .i = 10, .j = 20 };
toStr(NULL, &test, "test", TID(Test));
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment