Skip to the content.

Base Module

The base module (olib/olib_base.h) provides memory allocation functions and C/C++ compatibility macros.

Overview

This module defines:

Why Use This?

Memory Functions

olib_malloc

Allocate memory. Default implementation calls standard malloc.

Signature:

void* olib_malloc(size_t size);

Parameters:

Returns: Pointer to allocated memory, or NULL on failure

olib_free

Free previously allocated memory. Default implementation calls standard free.

Signature:

void olib_free(void* ptr);

Parameters:

olib_calloc

Allocate and zero-initialize memory. Default implementation calls standard calloc.

Signature:

void* olib_calloc(size_t num, size_t size);

Parameters:

Returns: Pointer to zero-initialized memory, or NULL on failure

olib_realloc

Resize previously allocated memory. Default implementation calls standard realloc.

Signature:

void* olib_realloc(void* ptr, size_t new_size);

Parameters:

Returns: Pointer to resized memory, or NULL on failure

Custom Allocator Setup

olib_set_memory_fns

Replace the default memory functions with custom implementations.

Signature:

void olib_set_memory_fns(
    olib_malloc_fn malloc_fn,
    olib_free_fn free_fn,
    olib_calloc_fn calloc_fn,
    olib_realloc_fn realloc_fn);

Parameters:

Notes:

Example:

#include <olib.h>

// Custom allocator tracking total allocations
static size_t total_allocated = 0;

void* my_malloc(size_t size) {
    total_allocated += size;
    return malloc(size);
}

void my_free(void* ptr) {
    free(ptr);
}

void* my_calloc(size_t num, size_t size) {
    total_allocated += num * size;
    return calloc(num, size);
}

void* my_realloc(void* ptr, size_t new_size) {
    return realloc(ptr, new_size);
}

int main(void) {
    // Set custom allocators before using olib
    olib_set_memory_fns(my_malloc, my_free, my_calloc, my_realloc);

    // Now use olib normally...
    olib_object_t* obj = olib_object_new(OLIB_OBJECT_TYPE_INT);
    olib_object_free(obj);

    printf("Total allocated: %zu bytes\n", total_allocated);
    return 0;
}

Function Pointer Types

typedef void* (*olib_malloc_fn)(size_t size);
typedef void (*olib_free_fn)(void* ptr);
typedef void* (*olib_calloc_fn)(size_t num, size_t size);
typedef void* (*olib_realloc_fn)(void* ptr, size_t new_size);

Macros

OLIB_API

Applied to all public API functions for proper symbol visibility in shared libraries.

OLIB_HEADER_BEGIN / OLIB_HEADER_END

Wraps header content for C++ compatibility:

OLIB_HEADER_BEGIN;  // extern "C" { in C++

// C declarations here

OLIB_HEADER_END;    // } in C++

Defines

Define Description
OLIB_SHARED Define when building/using olib as a shared library
OLIB_EXPORTS Define when building olib shared library (sets dllexport)