Skip to content

gb_rom_read_32bit()

Mr-PauI edited this page Dec 21, 2025 · 6 revisions

This function isn't defined by walnut-cgb. Each implementation must provide this function to gb_init(). The precise name of the function doesn't matter of course, but for consistency in this example the same name as the internal function pointer is used. May require -fno-strict-aliasing on some platforms

uint8_t* rom_data; // for this example a pointer to rom_data in ram, flash or psram data
uint32_t gb_rom_read_32bit(struct gb_s *gb, uint_fast32_t addr)
{
    const uint8_t *src = &rom_data[addr];

    // ESP32 series MCUs flash & PSRAM require 32-bit alignment for word loads
    if ((uintptr_t)src & 3) {
        // Safe fallback
        return  (uint32_t)src[0]
              | ((uint32_t)src[1] << 8)
              | ((uint32_t)src[2] << 16)
              | ((uint32_t)src[3] << 24);
    }

    // Aligned fast path
    return *(const uint32_t *)src;
}

an ISO C version can be written as follows:

uint8_t* rom_data; // for this example a pointer to rom_data in ram
uint32_t gb_rom_read_32bit(struct gb_s *gb, uint_fast32_t addr)
{
    /* ISO C version below */
    const uint8_t *src = &rom_data[addr];
    uint32_t val;
    memcpy(&val, src, sizeof(val));
    return val;
}

on platforms without any alignment performance or correctness concerns this could be simplified to something like

uint8_t* rom_data; // for this example a pointer to rom_data in ram, flash or psram data
uint32_t gb_rom_read_32bit(struct gb_s *gb, uint_fast32_t addr)
{
    return *(const uint32_t *)&rom_data[addr]; // may require -fno-strict-aliasing
}

or whatever is appropriate for your platform

Clone this wiki locally