Type Registration
This page explains how to register types for serialization.
Overview
Apache Fory™ requires explicit type registration for struct types. This design enables:
- Cross-Language Compatibility: Registered type IDs are used across language boundaries
- Type Safety: Detects type mismatches at deserialization time
- Polymorphic Serialization: Enables serialization of polymorphic objects via smart pointers
Registering Structs
Use register_struct<T>(type_id) to register a struct type:
#include "fory/serialization/fory.h"
using namespace fory::serialization;
struct Person {
std::string name;
int32_t age;
};
FORY_STRUCT(Person, name, age);
int main() {
auto fory = Fory::builder().xlang(true).build();
// Register with a unique type ID
fory.register_struct<Person>(100);
Person person{"Alice", 30};
auto bytes = fory.serialize(person).value();
auto decoded = fory.deserialize<Person>(bytes).value();
}
Type ID Guidelines
Type IDs must be:
- Unique: Each type must have a unique ID within a Fory instance
- Consistent: Same ID must be used across all languages and versions
User-registered type IDs are in a separate namespace from built-in type IDs, so you can start from 0:
// User type IDs can start from 0
fory.register_struct<Address>(0);
fory.register_struct<Person>(1);
fory.register_struct<Order>(2);