Sending data via TCP from Matlab to c

9 views (last 30 days)
Hi all I am trying to send data from matlab to c. In order to do so I am using the function fwrite.
My question is : how to send it as an struct ? for example
Msg.Size = int32(8);
Msg.Data = '12345678';
t = tcpip('10.1.4.34');
set(t, 'RemotePort', 55555)
set(t, 'InputBufferSize', 30000)
fopen(t)
It works OK When I execute the following
fwrite(t,Msg.Size,'int32');
fwrite(t,Msg.Data,'char');
How can I send the whole struct Msg ?
Any help will be appreciated.

Accepted Answer

Walter Roberson
Walter Roberson on 16 Feb 2011
Instead of writing the data directly to tcp, save it in a uint8 variable (use typecast() as necessary.) Once you have put together a block to send, the size of the uint8 variable is the message length and the uint8 array is the data. (Sometimes the message length has to include the size of the bytes used to represent the length.)
If you are working on the same system, you may find using memory mapping to be easier than tcp. See here
  1 Comment
zohar
zohar on 17 Feb 2011
Hi Walter and thanks again !
Your answer help me very much !
The solution :
Msg.Data = '12345678';
Msg.Size = int32(8 + 4); % 8 bytes for Msg.Data and 4 for Msg.Size
t = tcpip('10.1.4.34');
set(t, 'RemotePort', 55555)
set(t, 'InputBufferSize', 30000)
fopen(t)
TotalMsg = [typecast(Msg.Size,'int8') Msg.Data];% Msg.Data allready int8
fwrite(t,TotalMsg,'int8');
% another example
Msg.Data = int32(1:8);
Msg.Size = int32(length(Msg.Data)*4 + 4); % notice that Msg.Data is int32
TotalMsg = [typecast(Msg.Size,'int8') typecast(Msg.Data,'int8')];
fwrite(t,TotalMsg,'int8');
thanks

Sign in to comment.

More Answers (2)

Walter Roberson
Walter Roberson on 16 Feb 2011
You could loop through the fieldnames of the structure, detecting the type of the field and writing in the appropriate format, along with enough meta-information to be able to reconstruct it on the other side.
There are, however, some things that this cannot be applied to, such as certain kinds of objects. And sending a cell array of mixed data types gets you in to a mess.
Sometimes the easiest thing to do is to save() your data to a .mat file, transmit the .mat file as binary, write it out to disk, and load() it on the other side.
My understanding is that there are "serialize" methods for a number of objects, but it is not well documented as to how to access them.

zohar
zohar on 16 Feb 2011
Hi Walter
thank you for the quick response!
The c application require the massege length and its data.
How can I send them both?

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!