liblightmodbus 3.0
A lightweight, header-only, hardware-agnostic Modbus RTU/TCP library
Loading...
Searching...
No Matches
Custom allocators

Liblightmodbus allows users to define their custom functions for memory management. This functionality is provided with embedded systems in mind.

The user defined allocator is a function compatible with ModbusAllocator pointer type.

The allocator function must meet the following requirements:

  1. When size is 0, the memory allocated for the buffer (buffer->data) must be freed (if possible) and the buffer->data pointer should be set to NULL.
  2. When size is not 0, buffer->data should be set to point to a memory block of at least size bytes. If such block cannot be allocated, the allocator must return MODBUS_ERROR_ALLOC and free memory block pointed to by current buffer->data value. Consequently, buffer->data should be set to NULL.

Additionally:

  • All errors returned from the allocator when size is greater than zero will be reported by the library as MODBUS_GENERAL_ERROR(ALLOC).
  • Similar guarantee cannot be made for the case where size is 0. Then, errors reported by the allocator may or may not be reported by the library interface. This behavior might change depending on the context and in future versions of the library.
  • The user context pointer from ModbusMaster or ModbusSlave is provided to the callback via the void *context argument.
See also
modbusMasterSetUserPointer()
modbusSlaveSetUserPointer()

Static memory allocation

An example of a custom allocator relying only on statically allocated memory:

// !!! This only works if the allocator is used exclusively by a single instance of ModbusMaster or ModbusSlave !!!
LIGHTMODBUS_WARN_UNUSED ModbusError modbusStaticAllocator(ModbusBuffer *buffer, uint16_t size, void *context)
{
static uint8_t request[256];
if (!size)
{
// Pretend we're freeing the buffer
buffer->data = NULL;
return MODBUS_OK;
}
else
{
if (size > 256)
{
// Requested size is too big, return allocation error
buffer->data = NULL;
}
else
{
// Return a pointer to our buffer
buffer->data = request;
return MODBUS_OK;
}
}
}
#define LIGHTMODBUS_WARN_UNUSED
Definition base.h:19
ModbusError
Represtents different kinds of errors.
Definition base.h:137
@ MODBUS_ERROR_ALLOC
Memory allocation error.
Definition base.h:163
@ MODBUS_OK
No error.
Definition base.h:143
Stores a Modbus frame.
Definition base.h:276
uint8_t * data
Pointer to the frame buffer.
Definition base.h:280

One could also implement an allocator allocating memory from different statically allocated buffers based on buffer pointers, using the user context for bookkeeping.