This example demonstrates how to use Fory's high-performance serialization for C++ objects.
The easiest way to use Fory is with CMake's FetchContent module:
include(FetchContent) FetchContent_Declare( fory GIT_REPOSITORY https://github.com/apache/fory.git GIT_TAG main SOURCE_SUBDIR cpp ) FetchContent_MakeAvailable(fory) target_link_libraries(your_app PRIVATE fory::serialization)
cd examples/cpp/hello_world mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release cmake --build . --parallel ./hello_world
Or use the provided script:
./run.sh
From the repository root:
bazel build //examples/cpp/hello_world:hello_world bazel run //examples/cpp/hello_world:hello_world
Or use the provided script:
./run_bazel.sh
For your own project using Fory as a dependency:
MODULE.bazel.example to MODULE.bazel in your project rootBUILD.standalone to BUILD in your source directorylocal_path_override for local development# In your MODULE.bazel bazel_dep(name = "fory", version = "0.14.1") git_override( module_name = "fory", remote = "https://github.com/apache/fory.git", commit = "main", # Use specific commit for reproducibility ) # In your BUILD file cc_binary( name = "my_app", srcs = ["main.cc"], deps = ["@fory//cpp/fory/serialization:fory_serialization"], )
This example demonstrates:
FORY_STRUCT macro to register struct fieldsUse the FORY_STRUCT macro to register struct fields for serialization:
struct Point { int32_t x; int32_t y; }; FORY_STRUCT(Point, x, y);
auto fory = fory::serialization::Fory::builder() .xlang(true) // Enable cross-language serialization .track_ref(false) // Disable reference tracking .build(); // Register struct types with unique IDs fory.register_struct<Point>(1);
// Serialize Point point{10, 20}; auto bytes_result = fory.serialize(point); if (bytes_result.ok()) { auto bytes = bytes_result.value(); // Use bytes... } // Deserialize auto result = fory.deserialize<Point>(bytes.data(), bytes.size()); if (result.ok()) { Point deserialized = result.value(); }
# Link to serialization library target_link_libraries(your_app PRIVATE fory::serialization)
#include "fory/serialization/fory.h"