Descriptors vs C Strings (part 1)

| 1 Comment

The easiest way to learn about the descriptor is trough the equivalent code in C. In this post, I will write a short comparison, this article is inspired by the explanation about Symbian Descriptor on the the Professional Symbian Programming (I said inspired, my explanation is different, and the code in the copy of the book that I have is sometimes incorrect). In this part I will talk only about constant/immutable strings.

In C, if you define something like this:

static const char hellorom[] = "hello";

Then the string "hello" will be on a non-modifyable memory space (may be in ROM or RAM, but it can not be modified).

The equivalent code in Symbian is:

_LIT(KHelloROM, "hello");

Everything is still easy to understand here: you can not modify the contents of KHelloROM or hellorom. Something to note is that in Symbian the string is not NULL terminated, the length of the string is recorded in KHelloROM.

Now, in C, you can also have a pointer to the same location:

const char *helloptr = hellorom;

We can have that in Symbian:

TPtrC helloPtr(KHelloROM);

helloPtr contains a pointer to KHelloROM, and the length of the descriptor pointed by that pointer. You may think it is a bit strange: why do we need to store the length again?. The reason is that we can have a pointer to the first n part of the string, like this:

TPtrC ptr2(KHelloROM().Ptr(), 2);

If you try to display/print ptr2, it will say the string "he".

We can also put the "constant" data in stack (it will not become constant anymore, since stack is always writeable):



//this code is inside function
char hellostack[sizeof(hellorom)]; //sizeof counts the NULL terminator
strcpy(hellostack, hellorom);

This is a bit different in Symbian:

TBufC<5> helloStack(KHelloROM);

The string "hello" will live on the stack, along with the pointer and the length, but you can not modify the data through the variable helloStack. This is a bit useless, but using the TPtr class, you can still change the data (which is strange). I will discuss about this on part 2.

And you can put the string in the heap:


const char * s = strdup(hellorom);

In Symbian:

HBufC *h = KHelloROM().AllocL();

The HBufC class points to a data in the heap (that is owned by the object), and has a maximum length. Just like TBufC, this isn't really constant String (modifiable trough TPtr).

1 Comment

It was a good way to explore symbian by comparing with C

Leave a comment

About this Entry

This page contains a single entry by Yohanes Nugroho published on February 24, 2007 3:45 PM.

Porting to Series 60 3rd Edition: Handle the End Key was the previous entry in this blog.

Porting of S60Dict to 3rd edition is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.