C# Thrift Examples
As I mentioned in my earlier post I have been working with Facebook’s Thrift messaging project.
Unfortunately there are not currently any C# examples of how to use the Data Transfer Objects the Thrift compiler generates for us on the official wiki.
We managed to figure out how to do it by following the Java instructions and converting them into C# code. Before writing any code we need to import Thrift.dll into our Visual Studio project.
Assuming that we have the following Thrift definition file:
namespace csharp Test.Thrift
struct FooBarMessageThrift {
1: string Foo
2: string Bar
}
When we run the Thrift compiler we will end up with the FooBarMessageThrift class. I won’t post this class here as it’s all codegen.
The easiest way to transport this class around is by converting it to a byte array and transporting that:
var fooBarMessage = new FooBarMessageThrift {Foo = "foo", Bar = "bar"};
var stream = new MemoryStream();
TProtocol tProtocol = new TBinaryProtocol(new TStreamTransport(stream, stream));
fooBarMessage.Write(tProtocol);
byte[] content = stream.ToArray();
To read the byte array back into FooBarMessageThrift we do this:
var stream = new MemoryStream(content);
TProtocol tProtocol = new TBinaryProtocol(new TStreamTransport(stream, stream));
var barFooMessageThrift = new BarFooMessageThrift();
barFooMessageThrift.Read(tProtocol);
'content' in this example is the byte[] created in the first example, and that’s all there is to it!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.