Language Examples
This page shows the same steps in every language: create a message, write it into a frame, feed received bytes to a reader, and decode the frames that come out.
Proto Definition
Examples use this schema (example.sf):
package example;
message Status { option msgid = 1; uint32 id = 1; float value = 2;}Generate code for every language under generated/<lang>:
struct-frame example.sf --lang all --out generatedUsing Frame Profiles
Frame profiles provide complete framing and parsing functionality. This is the recommended approach for most applications.
Python with Profiles
# The --py-path directory must be on sys.pathimport syssys.path.insert(0, 'generated/py')
from structframe.frame_profiles import BufferWriter, AccumulatingReader, PROFILE_STANDARD_CONFIGfrom structframe.example import Status, get_message_info, decode_message
# Create and encode a message with a frame profilemsg = Status(id=42, value=3.14)writer = BufferWriter(PROFILE_STANDARD_CONFIG, 1024)writer.write(msg)frame_data = writer.data()
# Parse received framesreader = AccumulatingReader(PROFILE_STANDARD_CONFIG, get_message_info=get_message_info)reader.add_data(frame_data)
while (frame := reader.try_next()) is not None: decoded = decode_message(frame) # None for corrupt frames and other packages' IDs if isinstance(decoded, Status): print(f"ID: {decoded.id}, Value: {decoded.value}")Status.deserialize(frame) decodes one known type directly; decode_message picks the class from the frame’s message ID.
TypeScript with Profiles
import { Status, getMessageInfo, decodeMessage } from './generated/ts/example.structframe';import { BufferWriter, AccumulatingReader, ProfileStandardConfig } from './generated/ts/frame-profiles';
// Create and encode a message with a frame profileconst msg = new Status({ id: 42, value: 3.14 });const writer = new BufferWriter(ProfileStandardConfig, 1024);writer.write(msg);const frameData = writer.data();
// Parse received framesconst reader = new AccumulatingReader(ProfileStandardConfig, getMessageInfo);reader.addData(frameData);
let frame;while ((frame = reader.tryNext()) !== null) { const decoded = decodeMessage(frame); // undefined for corrupt frames and other IDs if (decoded instanceof Status) { console.log(`ID: ${decoded.id}, Value: ${decoded.value}`); }}The output folder’s index.ts re-exports the runtime and one namespace per package, so import { example, BufferWriter } from './generated/ts' also works (new example.Status(...)). Compare frame.msgId with Status.MSG_ID to dispatch by hand.
C++ with Profiles
#include <iostream>#include "example.structframe.hpp"#include "frame_profiles.hpp"
using namespace structframe;
// Create a messageexample::Status msg{};msg.id = 42;msg.value = 3.14f;
// Encode with a frame profileuint8_t buffer[1024];ProfileStandardWriter writer(buffer, sizeof(buffer));writer.write(msg);
// Parse received frames. The Profile*AccumulatingReader aliases take the// generated message-info function.ProfileStandardAccumulatingReader reader(example::get_message_info);reader.add_data(buffer, writer.size());
FrameMsgInfo result;while (reader.try_next(result)) { if (result.valid && result.msg_id == example::Status::MSG_ID) { example::Status decoded; decoded.deserialize(result); std::cout << "ID: " << decoded.id << ", Value: " << decoded.value << std::endl; }}ProfileReader<ProfileBulkConfig, 4096> gives a reader with a different buffer size. With several packages, include structframe_all.hpp and pass structframe::get_message_info, which knows every package.
C with Profiles
#include <stdio.h>#include "example.structframe.h" /* includes frame_profiles.h */
/* Create a message */ExampleStatus msg = {.id = 42, .value = 3.14f};
/* Encode with a frame profile. ExampleStatus_write fills in the message ID, * package ID and checksum magic bytes. */uint8_t buffer[1024];buffer_writer_t writer;buffer_writer_init(&writer, &PROFILE_STANDARD_CONFIG, buffer, sizeof(buffer));ExampleStatus_write(&writer, &msg);
/* Parse received frames */uint8_t internal[1024];accumulating_reader_t reader;accumulating_reader_init(&reader, &PROFILE_STANDARD_CONFIG, internal, sizeof(internal), example_get_message_info);accumulating_reader_add_data(&reader, buffer, buffer_writer_size(&writer));
frame_msg_info_t result;while (accumulating_reader_try_next(&reader, &result)) { if (result.valid && result.msg_id == EXAMPLE_STATUS_MSG_ID) { ExampleStatus decoded; ExampleStatus_deserialize(result.msg_data, result.msg_len, &decoded); printf("ID: %u, Value: %f\n", (unsigned)decoded.id, decoded.value); }}ExampleStatus_write_ext(&writer, &msg, seq, sys_id, comp_id) sets the sequence number and routing IDs on the profiles that carry them. With several packages, include structframe_all.h and pass structframe_all_get_message_info to the reader.
C# with Profiles
using StructFrame;using StructFrame.Framing;using StructFrame.Profiles;using StructFrame.Example;
// Create a messagevar msg = new Status { Id = 42, Value = 3.14f };
// Encode with a frame profilevar writer = new BufferWriter<StandardProfile>(1024);writer.Write(msg);byte[] frameData = writer.GetData();
// Parse received framesvar reader = new AccumulatingReader<StandardProfile>(getMessageInfo: MessageDefinitions.GetMessageInfo);reader.AddData(frameData);
while (reader.TryNext(out var result)){ if (result.Valid && MessageDefinitions.Deserialize(result) is Status decoded) { Console.WriteLine($"ID: {decoded.Id}, Value: {decoded.Value}"); }}Status.Deserialize(result) decodes one known type directly.
JavaScript with Profiles
const { Status, getMessageInfo, decodeMessage } = require('./generated/js/example.structframe');const { BufferWriter, AccumulatingReader, ProfileStandardConfig } = require('./generated/js/frame-profiles');
// Create and encode a message with a frame profileconst msg = new Status({ id: 42, value: 3.14 });const writer = new BufferWriter(ProfileStandardConfig, 1024);writer.write(msg);const frameData = writer.data();
// Parse received framesconst reader = new AccumulatingReader(ProfileStandardConfig, getMessageInfo);reader.addData(frameData);
let frame;while ((frame = reader.tryNext()) !== null) { const decoded = decodeMessage(frame); if (decoded instanceof Status) { console.log(`ID: ${decoded.id}, Value: ${decoded.value}`); }}Rust with Profiles
use struct_frame_sdk::example::Status;use struct_frame_sdk::prelude::*;
// Create and encode a message with a frame profilelet msg = Status { id: 42, value: 3.14 };let mut writer = BufferWriter::new(PROFILE_STANDARD_CONFIG, 1024);writer.write(&msg);
// Parse received frames. with_message_info stores the lookup function, so frames()// and next_frame() need no argument.let mut reader = AccumulatingReader::with_message_info(PROFILE_STANDARD_CONFIG, 4096, struct_frame_sdk::get_message_info);reader.add_data(writer.data());
for frame in reader.frames().filter(|f| f.valid) { if frame.msg_id == Status::MSG_ID { if let Some(decoded) = Status::deserialize(&frame) { println!("ID: {}, Value: {}", decoded.id, decoded.value); } }}writer.write_ext(&msg, seq, sys_id, comp_id) sets the sequence number and routing IDs on the profiles that carry them.
Direct Message Serialization
For cases where you need the message bytes without framing:
Python
import syssys.path.insert(0, 'generated/py')
from structframe.example import Status
msg = Status(id=42, value=3.14)data = msg.serialize()
received = Status.deserialize(data)print(f"ID: {received.id}, Value: {received.value}")TypeScript
import { Status } from './generated/ts/example.structframe';
const msg = new Status({ id: 42, value: 3.14 });const data = msg.serialize();
const received = Status.deserialize(data);console.log(`ID: ${received.id}, Value: ${received.value}`);JavaScript
const { Status } = require('./generated/js/example.structframe');
const msg = new Status({ id: 42, value: 3.14 });const data = msg.serialize();
const received = Status.deserialize(data);console.log(`ID: ${received.id}, Value: ${received.value}`);C++
#include "example.structframe.hpp"#include <iostream>
int main() { structframe::example::Status msg{}; msg.id = 42; msg.value = 3.14f;
uint8_t buffer[structframe::example::Status::MAX_SIZE]; size_t size = msg.serialize(buffer);
structframe::example::Status received; received.deserialize(buffer, size); std::cout << "ID: " << received.id << ", Value: " << received.value << std::endl; return 0;}C
#include <stdio.h>#include "example.structframe.h"
int main(void) { ExampleStatus msg = {.id = 42, .value = 3.14f};
uint8_t buffer[EXAMPLE_STATUS_MAX_SIZE]; size_t size = ExampleStatus_serialize(&msg, buffer);
ExampleStatus received; ExampleStatus_deserialize(buffer, size, &received); printf("ID: %u, Value: %f\n", (unsigned)received.id, received.value); return 0;}C#
using StructFrame.Example;
var msg = new Status { Id = 42, Value = 3.14f };byte[] data = msg.Serialize();
var received = Status.Deserialize(data);Console.WriteLine($"ID: {received.Id}, Value: {received.Value}");Communication Examples
Serial Communication (Python)
import sysimport serialsys.path.insert(0, 'generated/py')
from structframe.example import Status, get_message_infofrom structframe.frame_profiles import AccumulatingReader, PROFILE_STANDARD_CONFIG
ser = serial.Serial('/dev/ttyUSB0', 115200)reader = AccumulatingReader(PROFILE_STANDARD_CONFIG, get_message_info=get_message_info)
while True: reader.add_data(ser.read(ser.in_waiting or 1)) while (frame := reader.try_next()) is not None: if frame.valid and frame.msg_id == Status.MSG_ID: msg = Status.deserialize(frame) print(f"Received: ID={msg.id}, Value={msg.value}")Streaming Parser (C++)
#include "example.structframe.hpp"#include "frame_profiles.hpp"
using namespace structframe;
// Byte-by-byte streaming parser for UART/serial.ProfileStandardAccumulatingReader reader(example::get_message_info);
void on_byte_received(uint8_t byte) { if (auto result = reader.push_byte(byte)) { example::Status msg; msg.deserialize(result); std::cout << "ID: " << msg.id << std::endl; }}TCP Socket (TypeScript)
import * as net from 'net';import { Status, getMessageInfo } from './generated/ts/example.structframe';import { AccumulatingReader, ProfileStandardConfig } from './generated/ts/frame-profiles';
const client = net.createConnection({ port: 8080 });const reader = new AccumulatingReader(ProfileStandardConfig, getMessageInfo);
client.on('data', (data: Buffer) => { reader.addData(data); let frame; while ((frame = reader.tryNext()) !== null) { if (frame.valid && frame.msgId === Status.MSG_ID) { const msg = Status.deserialize(frame); console.log(`ID: ${msg.id}, Value: ${msg.value}`); } }});WebSocket (JavaScript)
const { Status, getMessageInfo } = require('./generated/js/example.structframe');const { AccumulatingReader, ProfileStandardConfig } = require('./generated/js/frame-profiles');const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');const reader = new AccumulatingReader(ProfileStandardConfig, getMessageInfo);
ws.on('message', (data) => { reader.addData(Buffer.from(data)); let frame; while ((frame = reader.tryNext()) !== null) { if (frame.valid && frame.msgId === Status.MSG_ID) { const msg = Status.deserialize(frame); console.log(`ID: ${msg.id}, Value: ${msg.value}`); } }});Frame Profiles
Different profiles for different use cases:
- ProfileStandard: General purpose (Basic header + Default payload)
- ProfileSensor: Low-bandwidth sensors (Tiny header + Minimal payload)
- ProfileIPC: Trusted inter-process (No header + Minimal payload)
- ProfileBulk: Large data transfers (Basic header + Extended payload)
- ProfileNetwork: Multi-system networks (Basic header + Extended Multi-System Stream payload)
All profiles support the same API: pass a different profile configuration (PROFILE_SENSOR_CONFIG, ProfileSensorConfig, StandardProfile → SensorProfile, and so on) to the same writer and reader types. C++ also offers aliases such as ProfileSensorWriter and ProfileSensorAccumulatingReader.
Arrays
Example with a bounded array:
message SensorData { option msgid = 2; repeated float readings = 1 [max_size=10];}A bounded array carries its element count. Each language exposes it as follows:
ExampleSensorData data = {0};data.readings.count = 3;data.readings.data[0] = 1.1f;data.readings.data[1] = 2.2f;data.readings.data[2] = 3.3f;structframe::example::SensorData data{};data.readings.count = 3;data.readings.data[0] = 1.1f;data.readings.data[1] = 2.2f;data.readings.data[2] = 3.3f;data = SensorData(readings=[1.1, 2.2, 3.3]) # the count is the list lengthconst data = new SensorData({ readingsCount: 3, readingsData: [1.1, 2.2, 3.3] });var data = new SensorData { ReadingsCount = 3 };data.ReadingsData[0] = 1.1f;data.ReadingsData[1] = 2.2f;data.ReadingsData[2] = 3.3f;let mut data = SensorData { readings_count: 3, readings: [0.0; 10] };data.readings[..3].copy_from_slice(&[1.1, 2.2, 3.3]);Serialization is the same as for any other message; variable messages encode only the used elements.
Nested Messages
Example with a nested message:
message Position { double lat = 1; double lon = 2;}
message Vehicle { option msgid = 3; uint32 id = 1; Position pos = 2;}ExampleVehicle v = {0};v.id = 1;v.pos.lat = 37.7749;v.pos.lon = -122.4194;structframe::example::Vehicle v{};v.id = 1;v.pos.lat = 37.7749;v.pos.lon = -122.4194;v = Vehicle(id=1, pos=Position(lat=37.7749, lon=-122.4194))// v.pos is a view into v's buffer, so assigning its fields writes through.const v = new Vehicle({ id: 1, pos: { lat: 37.7749, lon: -122.4194 } });v.pos.lat = 37.8;v.pos = new Position({ lat: 0, lon: 0 }); // or replace itvar v = new Vehicle { Id = 1, Pos = new Position { Lat = 37.7749, Lon = -122.4194 }};let v = Vehicle { id: 1, pos: Position { lat: 37.7749, lon: -122.4194 } };Key Takeaways
- Consistent API: Every language has a writer that frames a message (
write), a reader that takes the generated message-info function, anddeserialize(case varies by language convention). - Frame Profiles: Use a profile configuration with the BufferWriter and AccumulatingReader types for complete framing and parsing.
- Drain with
try_next: It returns every frame and every corrupt-frame event; checkvalid. - Decode by ID: Python
decode_message, TypeScript/JavaScriptdecodeMessageand C#MessageDefinitions.Deserializereturn the typed message for a frame; elsewhere comparemsg_idwith the type’sMSG_ID. - Variable Messages: Transparent handling - same API for fixed and variable-length messages.