Read struct data over UDP sent from a C program
4 views (last 30 days)
Show older comments
Hi all,
I need to read a struct data over a UDP connection, which is sent from a C program.
Is it possibile to read the UDP directly as struct? Just like we can read directly in C.
STRUCT_userdata *userdata=(STRUCT_userdata *)buf;
Any help is appreciate.
0 Comments
Answers (1)
Sameer
on 1 Mar 2024
Hi Shaily,
In MATLAB, you cannot directly cast a block of data received over UDP into a MATLAB structure as you might in C. Instead, you need to receive the data as a stream of bytes and then interpret these bytes according to the structure's layout defined in the C program.
Below is an example code to achieve this:
% Create a UDP object to connect to the host and port.
u = udp('127.0.0.1', 12345);
fopen(u);
% Read the data from the UDP object.
% Assuming you know the size of the data to read, for example, 1024 bytes.
data = fread(u, 1024, 'uint8');
% Now, assume the C struct is something like this:
% struct STRUCT_userdata {
% int id;
% float value;
% char name[10];
% };
% Convert the bytes to MATLAB data types.
% You need to know the exact order and size of the fields in the original struct.
id = typecast(data(1:4), 'int32'); % Convert first 4 bytes to an int
value = typecast(data(5:8), 'single'); % Convert next 4 bytes to a float
% For the string, you would need to handle it differently, since it's an array of chars.
name = char(data(9:18)); % Convert next 10 bytes to a char array
% Trim the null characters if the C string was null-terminated.
name = deblank(name);
% Close the UDP connection.
fclose(u);
delete(u);
clear u;
% Now you can use id, value, and name as if they were fields in a struct.
userdata.id = id;
userdata.value = value;
userdata.name = name;
This is a simplified example and assumes that the data is packed in the same way that MATLAB will interpret it. In some cases, you may need to account for endianness and padding, which can differ between systems. If the C struct uses padding or is packed in a non-standard way, you'll need to adjust the MATLAB code to match the exact memory layout of the struct
Please refer to the link below for more information regarding UDP:
I hope this helps!
Sameer
0 Comments
See Also
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!