I'm interested in how you can write data in a particular structure to a pre-allocated memory block.
The idea is to write down the render commands and then read them in a loop. The problem is that allocating and deleting memory every cycle, which is 60 times per second is bad and I want to ask how can I write and read different types of data to the buffer.
example:
struct cmd_viewport {
int x, y, w, h;
};
struct cmd_line {
int x0, y0, x1, y1;
unsigned int width;
};
void* buffer_alloc(void* buffer, size_t offset, size_t size) {
...
}
void* buffer_get_ptr(void* buffer, size_t offset) {
...
}
int main(int argc, char* argv) {
void* cmd_buffer;
struct cmd_viewport* viewport;
struct cmd_line* line;
struct cmd_line* line2;
cmd_buffer = malloc(1024);
if (cmd_buffer == NULL) {
return EXIT_FAILURE;
}
viewport = (struct cmd_viewport*)buffer_alloc(cmd_buffer, 0, sizeof(struct cmd_viewport));
line = (struct cmd_line*)buffer_alloc(cmd_buffer, sizeof(struct cmd_viewport), sizeof(struct cmd_line));
/* it must be a direct write to the cmd_buffer memory location */
viewport->x = 0;
viewport->y = 0;
viewport->w = 800;
viewport->h = 600;
line->x0 = 100;
line->y0 = 100;
line->x1 = 300;
line->y1 = 400;
line->width = 2;
line2 = (struct cmd_line*)buffer_get_ptr(cmd_buffer, sizeof(struct cmd_viewport));
printf("line->width = %d\n", line2->width);
free(cmd_buffer);
return EXIT_SUCCESS;
}
How can you make a void* buffer cast from a specific offset to any data type ?