I am trying to send a float over the network from a program written in c# on windows to an android application written in java using flatbuffers.
From the received bytes in the android application a buffer is build using java.nio.ByteBuffer.wrap. From this buffer the Example object is deserialized. This however results in every float being set to 0.
In the example below this behavior is shown.
Why does "example2" return the value 0.0
instead of 20.0
?
This is the schema i use:
// Example IDL file for our monster's schema.
namespace MyGame.Sample;
table Example {
myFloat:float;
}
root_type Example;
This is the java code which show the behaviour:
//The float
float myFloat = 20.0f;
FlatBufferBuilder builder = new FlatBufferBuilder(0);
//Build the example
Example.startExample(builder);
Example.addMyFloat(builder, myFloat);
int exampleInt = Example.endExample(builder);
builder.finish(exampleInt);
java.nio.ByteBuffer buf = builder.dataBuffer();
Example example = Example.getRootAsExample(buf);
System.out.println("1: Myfloat: " + example.myFloat());
byte[] bytesBuf = buf.array();
Example example2 = Example.getRootAsExample(java.nio.ByteBuffer.wrap(bytesBuf));
System.out.println("2: Myfloat: " + example2.myFloat());
Output:
System.out: 1: Myfloat: 20.0
System.out: 2: Myfloat: 0.0
array() gets the raw underlyimg buffer, which contains the FlatBuffer at an offset possibly other than 0. Instead, there's a method in FlatBufferBuilder (whose name escapes me right now) that will get you the buffer.