C Tutorial

Sending and receiving LCM messages with C


This tutorial will walk you through the main tasks for exchanging messages using the LCM C API. It covers the following topics:

This tutorial uses the example_t message type defined in the type definition tutorial, and assumes that you have generated the C bindings for the example type by running

1 lcm-gen -c example_t.lcm

After running this command, you should have two files: exlcm_example_t.c and exlcm_example_t.h. These two files are the C bindings for the example message type. Notice that the message type package name "exlcm" was prepended to the file name. This is how LCM emulates namespaces in C, and the package name is also prefixed to the generated C struct name. If you have the time, take a moment to open up those two files and inspect the generated code.

Initializing LCM

The first task for any application that uses LCM is to initialize the library. Here's an example of that (and how to clean up after itself as well):

1 #include <lcm/lcm.h>
3 int main(int argc, char ** argv)
4 {
5  lcm_t * lcm = lcm_create(NULL);
7  if(!lcm)
8  return 1;
10  /* Your application goes here */
12  lcm_destroy(lcm);
13  return 0;
14 }

The function lcm_create() allocates and initializes an instance of lcm_t, which represents a connection to an LCM network. The single argument can be NULL as shown above, to initialize LCM with default settings. The defaults initialized are suitable for communicating with other LCM applications on the local computer. The argument can also be a string specifying the underlying communications mechanisms. For communication across computers, or other usages such as reading data from an LCM logfile (e.g., to post-process or analyze previously collected data), see the API reference for lcm_create().

Once you're all done, it's a good idea to call lcm_destroy() to clean up any resources used by LCM.

Publishing a message

When you create an LCM data type and generate C code with lcm-gen, that data type will then be available as a C struct with the same name. For example_t, the C struct that gets generated looks like this:

1 typedef struct _exlcm_example_t exlcm_example_t;
2 struct _exlcm_example_t
3 {
4  int64_t timestamp;
5  double position[3];
6  double orientation[4];
7  int32_t num_ranges;
8  int16_t *ranges;
9  char* name;
10  int8_t enabled;
11 };

Notice here that fixed-length arrays in LCM appear as fixed-length C arrays. Variable length arrays appear as pointers in C. More on that below.

We can instantiate and then publish some sample data as follows:

1 #include <lcm/lcm.h>
2 #include "exlcm_example_t.h"
4 int
5 main(int argc, char ** argv)
6 {
7  lcm_t * lcm = lcm_create(NULL);
8  if(!lcm)
9  return 1;
11  exlcm_example_t my_data = {
12  .timestamp = 0,
13  .position = { 1, 2, 3 },
14  .orientation = { 1, 0, 0, 0 },
15  };
16  int16_t ranges[15];
17  int i;
18  for(i = 0; i < 15; i++)
19  ranges[i] = i;
21  my_data.num_ranges = 15;
22  my_data.ranges = ranges;
23 = "example string";
24  my_data.enabled = 1;
26  exlcm_example_t_publish(lcm, "EXAMPLE", &my_data);
28  lcm_destroy(lcm);
29  return 0;
30 }

The full example is available in runnable form as examples/c/send_message.c in the LCM source distribution.

For the most part, this example should be pretty straightforward. Note that my_data.ranges refers to a variable length array defined by the example_t LCM type, and is represented by a pointer in the generated C struct. It is up to the programmer to set this pointer to an array of the proper type, and set my_data.num_ranges to a value smaller or equal to the number of elements in that array. When the message is encoded, my_data.num_ranges determines how many elements will actually be read and transmitted from my_data.ranges. If my_data.num_ranges is set to 0, the value of my_data.ranges is ignored.

The call to exlcm_example_t_publish() serializes the data into a byte stream and transmits the packet using LCM to any interested receivers. The string "EXAMPLE" is the channel name, which is a string transmitted with each packet that identifies the contents to receivers. Receivers subscribe to different channels using this identifier, allowing uninteresting data to be discarded quickly and efficiently.

Receiving LCM Messages

As discussed above, each LCM message is transmitted with an attached channel name. You can use these channel names to determine which LCM messages your application receives, by subscribing to the channels of interest. It is important for senders and receivers to agree on the channel names which will be used for each message type.

Here is a sample program that sets up LCM and adds a subscription to the "EXAMPLE" channel. Whenever a message is received on this channel, its contents are printed out. If messages on other channels are being transmitted over the network, this program will not see them because it only has a subscription to the "EXAMPLE" channel. A particular instance of LCM may have an unlimited number of subscriptions.

1 #include <stdio.h>
2 #include <inttypes.h>
3 #include <lcm/lcm.h>
4 #include "exlcm_example_t.h"
6 static void
7 my_handler(const lcm_recv_buf_t *rbuf, const char * channel,
8  const exlcm_example_t * msg, void * user)
9 {
10  int i;
11  printf("Received message on channel \"%s\":\n", channel);
12  printf(" timestamp = %"PRId64"\n", msg->timestamp);
13  printf(" position = (%f, %f, %f)\n",
14  msg->position[0], msg->position[1], msg->position[2]);
15  printf(" orientation = (%f, %f, %f, %f)\n",
16  msg->orientation[0], msg->orientation[1], msg->orientation[2],
17  msg->orientation[3]);
18  printf(" ranges:");
19  for(i = 0; i < msg->num_ranges; i++)
20  printf(" %d", msg->ranges[i]);
21  printf("\n");
22  printf(" name = '%s'\n", msg->name);
23  printf(" enabled = %d\n", msg->enabled);
24 }
26 int
27 main(int argc, char ** argv)
28 {
29  lcm_t * lcm = lcm_create(NULL);
30  if(!lcm)
31  return 1;
33  exlcm_example_t_subscribe(lcm, "EXAMPLE", &my_handler, NULL);
35  while(1)
36  lcm_handle(lcm);
38  lcm_destroy(lcm);
39  return 0;
40 }

The full example is available in runnable form as examples/c/listener.c in the LCM source distribution.

A key design principal for this subscription code is that it is event driven. The application supplies a callback function to example_t_subscribe() that is called whenever a message is available. This happens inside a single thread without need for concurrency, since the callback is dispatched from within the lcm_handle() function.

It is important to call lcm_handle() whenever work needs to be done by LCM. If no work is needed, the function will block until there is. For applications without another type of main loop, it is suitable to call lcm_handle() in a loop as seen above. However, many applications already use some type of event loop. In these cases, it is best to monitor the LCM file descriptor, which can be obtained with lcm_get_fileno(). Whenever this file descriptor becomes readable, the application should call lcm_handle() which is guaranteed to not block in such a situation. Additional examples for doing this can be found in examples/c, in the LCM source distribution.