getting args of a message - memory handling

Fritz Code codefritz at googlemail.com
Sat May 24 05:02:04 PDT 2008


Hi,

studying the low level API Tutorial at
http://dbus.freedesktop.org/doc/api/html/index.html
I want to make sure that I've understood the concept of getting arguments of
a received message correctly.

If I want to keep the  argument of a received message I have to allocate new
memory and copy the value of the argument (which is presented by a pointer).
After that I have to unref the message.
Here an example of a possible function (pseudo-code):

char * myReceiveMethod(void){
  DBusMessage* msg;
  DBusMessage* reply;
  char *resultarg;
  char *buf=NULL;

  (....)

   if (!dbus_message_get_args (reply, &err,
                  DBUS_TYPE_STRING, &resultarg,
                  DBUS_TYPE_INVALID)){
      fprintf (stderr, "Failed to complete ListServices call: %s\n",
           err.message);
      exit (1);
   }

   //copy value of received argument and make necessary memory allocation
   buf = (char *)malloc(sizeof(char) * (strlen(resultarg) +1));
   strcpy(buf, resultarg);
   //unref messages,
   dbus_message_unref(reply);
   dbus_message_unref(msg);

   return buf; //return pointer, to do anything with it, of course it still
must be "free'ed" when Im done with it ( free() )
}

The adress where resultarg points to is not valid anymore after the reply
was unrefed, right?



Handling reply arguments of type array is different.
Here you don't have to allocate new memory If you want to keep the
arguments.
But you have to free the memory after the message reply was unrefed,
although you haven't allocated the memory.
Example:

char ** myMethod(){
  DBusMessage* msg;
  DBusMessage* reply;
  char **services;
  int servicesCount=0

(...)

 if (!dbus_message_get_args (reply, &err,
                  DBUS_TYPE_ARRAY,DBUS_TYPE_STRING,
                  &services,&servicesCount,
                  DBUS_TYPE_INVALID)){
      fprintf (stderr, "Failed to complete GetRemoteServiceClasses call:
%s\n",
           err.message);

  dbus_message_unref(reply);
  dbus_message_unref(msg);


  //  for (i = 0; i < servicesCount; i++)
  //   free (services[i]);
  //  free (services);

//

  return services;
  }


Of course I still have to free the services when Im done with them, e.g.
before exiting the application, for example wit the following code:
    for (i = 0; i < servicesCount; i++)
     free (services[i]);
    free (services);


Thanks for your comments and hints.

-- 
Regards,
--Codefritz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.freedesktop.org/archives/dbus/attachments/20080524/4873ddeb/attachment.html 


More information about the dbus mailing list