Experimental. This walks through a complete zero app, which the repository builds from the NuGet packages on every change (
samples/HelloZero), so the code below is known to work.
Prerequisites
- Windows x64
- the .NET 10 SDK
- the MSVC C++ build tools: install “Desktop development with C++” from the Visual Studio
installer. Native AOT links with
link.exe.
The project
A zero app is an ordinary project file using the protobuf-net.Zero.Sdk project SDK, plus the
protobuf-net.Zero package. Put the latest versions from NuGet in place of 0.1.N-alpha:
<Project Sdk="protobuf-net.Zero.Sdk/0.1.N-alpha">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="protobuf-net.Zero" Version="0.1.N-alpha" />
</ItemGroup>
</Project>
The SDK does all the unusual work. It removes the .NET framework, supplies a minimal
System.Runtime in its place, and sets up Native AOT to link with nothing but kernel32. (It has
to be an SDK, not a package reference, because the framework has to be gone before NuGet restore
runs.)
A contract
Annotate a partial struct, exactly as you would a protobuf-net contract:
using System;
using ProtoBuf.Zero;
[ProtoContract]
internal ref partial struct Greeting
{
[ProtoMember(1)] public int Id;
[ProtoMember(2)] public string Text;
[ProtoMember(3, IsPacked = true)] public ReadOnlySpan<int> Values;
}
It is a ref struct only because it holds a span; a contract with no spans can be a plain struct.
The generator supplies the rest of the partial struct: a Measure and a Write method.
Writing
There is no allocator, so you supply the buffer. Measure first if you need to know the size:
Greeting greeting = default;
greeting.Id = 150;
greeting.Text = "hi";
greeting.Values = [1, 2]; // constant data in the image: no array, no allocation
Buffer64 storage = default; // a stack buffer (see below)
Span<byte> buffer = storage;
if (!ProtoSerializer.TrySerialize(in greeting, buffer, out int written)) return 2;
ReadOnlySpan<byte> bytes = buffer.Slice(0, written);
// 08 96 01 12 02 68 69 1A 02 01 02 - byte for byte what protobuf-net writes
Nothing throws. TrySerialize returns false if the buffer is too small, and
ProtoSerializer.Measure(in greeting) gives the exact size up front.
stackalloc is not available in a zero app: it makes the compiler emit stack-cookie checks, and
the cookie lives in a C runtime that a zero app does not link. An inline array does the same job
as an ordinary struct:
[InlineArray(64)]
internal struct Buffer64 { private byte _element; }
Reading
A message is read into a view: a ref struct that borrows from the payload instead of copying
it. A string arrives as its UTF-8 bytes, and a repeated field is decoded lazily by foreach, so a
view needs no storage at all. For now you write the view yourself. It is a loop over the fields:
internal ref struct GreetingView : IProtoView<GreetingView>
{
public int Id;
public ReadOnlySpan<byte> Text; // UTF-8, borrowed from the payload
public RepeatedInt32 Values; // decoded lazily, by foreach
public static bool TryMerge(ref ProtoReader reader, ref GreetingView value)
{
ReadOnlySpan<byte> body = reader.Remaining; // what repeated fields read from
while (reader.TryReadTag(out int field, out WireType wireType))
{
bool ok = field switch
{
1 when wireType == WireType.Varint => reader.TryReadInt32(out value.Id),
2 when wireType == WireType.LengthDelimited => reader.TryReadLengthDelimited(out value.Text),
3 => RepeatedInt32.TryAccumulate(ref reader, wireType, body, 3, ref value.Values),
_ => reader.TrySkip(field, wireType), // unknown fields are skipped
};
if (!ok) return false;
}
return reader.AtEnd;
}
}
and then:
// `scoped`: the view borrows from `storage`, which lives on this method's stack
scoped GreetingView view = default;
if (!ProtoSerializer.TryDeserialize(bytes, ref view)) return 3;
foreach (int value in view.Values) { /* 1, then 2 */ }
TryDeserialize returns false for truncated or malformed input rather than throwing. A repeated
field is accepted packed or unpacked, and its occurrences may be scattered through the message, as
the protobuf spec requires.
Building
dotnet publish -c Release
The exe is in bin/Release/net10.0/win-x64/publish/. For this sample it is about 17 KB.
If the link step fails with an error naming link.exe, the build could not find MSVC. Add the
Visual Studio installer directory, which holds vswhere.exe, to PATH:
set PATH=%PATH%;%ProgramFiles(x86)%\Microsoft Visual Studio\Installer
Talking to the outside world
There is no Console, File or Socket. Declare the OS functions you need and call them. The
SDK binds kernel32 statically, so these resolve at link time:
[DllImport("kernel32")] static extern nint GetStdHandle(int handle);
[DllImport("kernel32")] static extern int WriteFile(nint h, byte* buffer, int count, int* written, void* overlapped);
Using it from ordinary .NET
The same protobuf-net.Zero package works in any .NET 10 project, with no SDK:
<PackageReference Include="protobuf-net.Zero" Version="0.1.N-alpha" />
The contract and view above compile unchanged, and repeated members can also be List<T> or
arrays there. The same contract source can then be shared between a zero app and a normal one.