Search code examples
ctypesreturn

Return "data type" in C


I want to have a simple

something Data() {
    return int;
}

or use char, long ... w/e

How would I go about this?

I don't want to return a number, or a string, I want to return the data type

Another option I have tried is using a macro

#define Data int

and using different ifs and elses, I could use that instead, but I can't use pointers in the macros, so that's a problem as well (I need to return the data type based on a number saved in a pointer).

Here is the exact problem I have, and what I have done so far:

//Read/write any type from memory
#define MemRead(type, offset) (*((type*)(memory + (offset))))
#define MemSet(type, offset, value) (*((type*)(memory + (offset))) = (value))

//Get the index for type (0 - char, 1 - short, 2 - int ...)
#define TypeIndex (MemRead(unsigned short, 0) % 4)
//#if TypeIndex == 0
//#define TYPE char
//#elif TypeIndex == 1
//#define TYPE short
//#endif

//#define TYPE SOMETHING HERE maybe an if-else ...
//#if TypeIndex == 0 doesn't work, because I can't use * in macros

char *memory = NULL;

void memory_init() {

    memory = (char*)ptr;

    //Create a list of pointers
    int numOfPointers = 1, tsize = size - 3 * IntSize - START;
    while (tsize > 64) {
        tsize /= 4;
        MemSet(int, numOfPointers++ * IntSize - 3, 0);
    }

    int typeIndex = 0;
    if (size < power(2, (sizeof(short) * 8) - 1)) {
        typeIndex = 1;
    }
    else if (size < power(2, (sizeof(int) * 8) - 1)) {
        typeIndex = 2;
    }
    else {
        typeIndex = 3;
    }

    MemSet(unsigned char, 0, numOfPointers * 4 + typeIndex);
    MemSet(int, HEADER - IntSize, 0);

    int memAvailable = size - HEADER - 3 * IntSize;
    setBoundaries(HEADER + IntSize, memAvailable, memAvailable);
    MemSet(int, size - IntSize, 0);

    //Set beginning pointer
    MemSet(int, HEADER - IntSize, HEADER + IntSize);

    //Set pointers inside the free block
    MemSet(int, HEADER + IntSize, NULL);
    MemSet(int, HEADER + 2 * IntSize, HEADER - IntSize);
}


int main() {

    char region[500];
    memory_init(region, 500);
}

I get some memory space, set the first char to be an index showing what data type I will be using and how many pointers there will be on lists (each list contains different sized free blocks), and I can't get to get the type from TYPE.

I could possibly use a switch in each function to work with different data types based on the first index in memory, but that's something ugly and a reason why I am looking for a better solution.


Solution

  • So, instead of trying to get a macro on the type, I can just use function which will write the desired number in whatever type the flag is set to:

    void MemRead(int offset) {
        switch(flag something something) {
            case 1 //for char
            case 2 //for short etc etc
        }
    }
    

    Easy as that