Decoding char* from ofBuffer

Hey folks, I’m having some trouble with passing binary data with ofBuffers.

I have the following struct:

struct TrafficData
{
	float positionX;
	float positionY; 
	float positionZ;
	float facingAngle;
	float speed;
	JointData joints[25];
};

I need to serialize it as binary to send it over websockets. I’m encoding and decoding it for test purposes, this way:

TrafficData test;
test.positionX = 0.1;
test.positionY = 0.2;
test.positionZ = 0.3;

char sendData[sizeof(test)];
memcpy(sendData, &test, sizeof(test));

TrafficData temp1;
memcpy(&temp1, sendData, sizeof(sendData));
ofLog() << temp1.positionX << " : " << temp1.positionY << " : " << temp1.positionZ;

Doing this, the log shows the exact values I defined on my test object, 0.1 : 0.2 : 0.3. But I’m using ofxLibwebsockets, which encapsulates the values in an ofBuffer, and when I received and decoded them it was completely wrong, so I did this test case:

TrafficData test;
test.positionX = 0.1;
test.positionY = 0.2;
test.positionZ = 0.3;

char sendData[sizeof(test)];
memcpy(sendData, &test, sizeof(test));

ofBuffer buffer;
buffer.set(sendData, sizeof(sendData));

char *tempData = buffer.getData();

TrafficData temp2;
memcpy(&temp2, tempData, sizeof(tempData));
ofLog() << temp2.positionX << " : " << temp2.positionY << " : " << temp2.positionZ;

This time, my log shows 0.1 : -1.07374e+08 : -1.07374e+08. Does anybody have any idea on why it’s behaving like this? Is it related to the way I’m encoding and decoding, or is it based on the fact that the buffer on ofBuffer is stored as a std::vector<char> instead of a char*? Anyway, how can I get the correct value?

Thanks in advance!

Solved my own issue! The size was not correct, I just needed to change the following:

ofBuffer buffer;
buffer.set(sendData, sizeof(sendData));

int size = buffer.size() * sizeof(char);
char *tempData = buffer.getData();
	
TrafficData temp;
memcpy(&temp, tempData, size);

ofLog() << temp.positionX << " : " << temp.positionY << " : " << temp.positionZ;

Then it logged correctly the values 0.1 : 0.2 : 0.3

Hello,
I was wondering, would something similar allow me to load and then print out xyz floats from a .ply file?

I’m not sure about .ply files’ structure, but I believe it would be a start. But I think it’s better if you start another thread on it, as people will be able to help you more there.

yup i’ve improved my existing post here, fingers crossed