Last active
October 18, 2020 11:16
-
-
Save mrtrizer/ab4e3bc0304eceda4eaf9c9934dafa67 to your computer and use it in GitHub Desktop.
C language macro-intense reflection for functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
// Make a FOREACH macro | |
#define FE_0() | |
#define FE_1(X) *((X*)(args[0])) | |
#define FE_2(X, ...) FE_1(__VA_ARGS__), *((X*)(args[1])) | |
#define FE_3(X, ...) FE_2(__VA_ARGS__), *((X*)(args[2])) | |
#define FE_4(X, ...) FE_3(__VA_ARGS__), *((X*)(args[3])) | |
#define FE_5(X, ...) FE_4(__VA_ARGS__), *((X*)(args[4])) | |
#define FE_6(X, ...) FE_5(__VA_ARGS__), *((X*)(args[5])) | |
#define FE_7(X, ...) FE_6(__VA_ARGS__), *((X*)(args[6])) | |
#define FE_8(X, ...) FE_7(__VA_ARGS__), *((X*)(args[7])) | |
#define FE_9(X, ...) FE_8(__VA_ARGS__), *((X*)(args[8])) | |
#define FE_10(X, ...) FE_9(__VA_ARGS__), *((X*)(args[9])) | |
//... repeat as needed | |
#define GET_MACRO(_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,NAME,...) NAME | |
#define FOR_EACH(...) \ | |
GET_MACRO(_0,__VA_ARGS__,FE_10,FE_9,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1,FE_0)(__VA_ARGS__) | |
#define REFLECT_FUNC(ResultT, funcName, ...) \ | |
\ | |
ResultT funcName (__VA_ARGS__);\ | |
\ | |
void call_##funcName(void* args[], size_t n, void* result)\ | |
{\ | |
(void)n;\ | |
*(ResultT*)result = funcName(FOR_EACH(__VA_ARGS__));\ | |
}\ | |
\ | |
FuncReflection reflect_##funcName()\ | |
{\ | |
FuncReflection reflection = {\ | |
.name = #funcName,\ | |
.args = NULL,\ | |
.argsN = 2,\ | |
.resultTypeName = NULL,\ | |
.func = call_##funcName\ | |
};\ | |
return reflection;\ | |
} | |
typedef struct { | |
char* name; | |
size_t size; | |
} TypeReflection; | |
typedef struct { | |
char* name; | |
char* typeName; | |
} ArgReflection; | |
typedef struct { | |
char* name; | |
ArgReflection** args; | |
size_t argsN; | |
char* resultTypeName; | |
void (*func)(void*[], size_t, void*); | |
} FuncReflection; | |
int testFunc (int a, int b) | |
{ | |
return a + b; | |
} | |
REFLECT_FUNC(int, testFunc, int, int) | |
int main() | |
{ | |
//REGISTER_FUNC(reflection, testFunc); | |
int arg1 = 2; | |
int arg2 = 7; | |
void* argPtrs[] = {&arg1, &arg2}; | |
int result; | |
reflect_testFunc().func(argPtrs, 2, &result); | |
printf ("result: %d\n", result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment