vendredi 22 mars 2019

How to assign functions to a function pointer?

I am coding a Gameboy Emulator, and for the CPU's instructions I use this struct here (in cpp.hpp) to store info about them. The map is used to access all this information through a key equal to its personal opcode:

    struct instruction {
        std::string name;    //name of the instruction
        int cycles;          //clock cycles required to be executed
        int paramNum;        //number of params accepted
        void* function;      //code to be executed
    };
    class Cpu {
        private:
            std::map<unsigned char, instruction> instrMap;
            void Cpu::fillInstructions(void);
            instruction addInstruction(std::string, int, int, void*);
        public:
            void add_A_n(unsigned char);
    }

Then in the cpu.cpp I have for example one of the function I want to cast to a function pointer in order to be assigned to the field of the struct instruction. So I have this code:

    void Cpu::add_A_n(unsigned char n) {
        //body     
    }
    void Cpu::addInstructions(std::string name, int cycles, int paramNum, void* function) {
        instruction i = {name, cycles, paramNum, function};
        return i;
    }
    void Cpu::fillInstructions() {
        instrMap[0x80] = Cpu::addInstruction("ADD A, n", 4, 0, (void*)&Cpu::add_A_n);
    }

The goal is to fetch the opcode from the memory, then to use this opcode to retrieve from the map the information about the relative instruction, and finally to execute its function by using a switch case to select the right one:

    ((void (*)(void))instrMap[0x80].function)(); //for 0 params
    ((void (*)(unsigned char))instrMap[0x90].function)((unsigned char)operand); //for 1 param

My goal is to cast the all the functions, even the ones who requires some parameters, to the one in the struct.

The respective function it is correctly executed, but a warning is raised:

warning: converting from 'void (Cpu::)()' to 'void' [-Wpmf-conversions] instrMap[0x80] = Cpu::addInstruction("ADD A, n", 4, 0, (void*)&Cpu::add_A_n);

How can I solve it and why does it occur? Thanks

Aucun commentaire:

Enregistrer un commentaire