Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 24
Текст из файла (страница 24)
Only buffers that can explicitly be owned and releasedby the RBuf are supported. On construction, this is limited to HBufC,as others are ambiguous. Using the Assign() method discussed below,flat-heap-byte TUint arrays and existing RBufs are also supported:these are not supported through constructors, however, as the ownershiptransfer is not clear enough.CreationHaving constructed an RBuf that owns no data, data or space for datacan be associated with the RBuf using the Create() method. TheCreate() methods return a standard error code, usually KErrNone, ifsuccessful, or KErrNoMemory, if there is insufficient memory. For all theCreate() methods (including CreateMax()), there are correspondingCreateL() methods that leave on failure.To simply allocate space for data, without specifying the data itself, use:RBuf myRBuf;TInt maxSizeOfData = 20;if (myRBuf.Create(maxSizeOfData)) != KErrNone){...// error handling// Handling potential errors is omitted// from subsequent code examples for clarity.}The size of the descriptor data after running the above code is setto zero.
To set the size of the data to the maximum (i.e., equal to themaxSizeOfData parameter), use the CreateMax() method instead.It is also possible to create an RBuf with its data initialized. Forexample, to copy the contents of another descriptor into an RBuf, specifythe other descriptor as a parameter to the Create() or CreateL()method:RBuf myRBuf;TBufC<20> myTBufC (_L("Descriptor data"));myRBuf.CreateL(myTBufC);This sets the maximum size of the RBuf to the length of the sourcedescriptor. To specify a maximum size larger or smaller than this, passthe maximum size as the second parameter to the Create() method:RBuf myRBuf;_LIT(KGenesis, "In principio creavit Deus caelum et terram.");TInt maxSizeOfData = 30;myRBuf.CreateL(KGenesis(), maxSizeOfData); // trims text to 30// charactersHEAP DESCRIPTORS105A final option allows the contents of an RBuf’s data to be set froma stream which contains the length of the data followed by the dataitself.
Both the stream and the maximum permitted size of the streamare specified as parameters to the CreateL() method – there is noCreate() method available for setting an RBuf from a stream:RBuf myRBuf;RReadStream myStream;TInt maxSizeOfData = 30;myRBuf.CreateL(myStream, maxSizeOfData);Note that Create() orphans any data already owned by the RBuf,so Close() should be called where appropriate to avoid memory leaks.AssignmentAn RBuf can take ownership of a pre-allocated heap descriptor, use:HBufC* myHBufC = HBufC::NewL(20);RBuf myRBuf.Assign(myHBufC);To transfer ownership of another RBuf, the RBuf is specified as theparameter to the Assign() method:RBuf myRBuf1;RBuf myRBuf2;HBufC* myHBufC = HBufC::NewL(20);myRBuf1.Assign(myHBufC); // take ownership of heap memorymyRBuf2.Assign(myRBuf1); // take ownership of another RBufmyRBuf2.Close();Finally, the RBuf can take ownership of pre-allocated memory on theheap by specifying the heap cell and the maximum size of the data:TInt maxSizeOfData = 20;RBuf myRBuf;TUint16* pointer = static_cast<TUint16*>(User::AllocL (maxSizeOfData*2));myRBuf.Assign(pointer, maxSizeOfData);For this call, the current size of the descriptor is set to zero.
To specifya different size, insert this value as the second parameter. As an example,the last line of the code snippet above could be replaced by:TInt currentSizeOfData = maxSizeOfData / 2;myRBuf.Assign(pointer, currentSizeOfData, maxSizeOfData);106DESCRIPTORSNote that Assign() orphans any data already owned by the RBuf,so Close() should be called where appropriate to avoid memory leaks.The Swap() method allows the contents of two RBufs to be exchanged.ReallocationHaving created an RBuf, the data space in the descriptor can be resizedif the data should exceed the size of the descriptor.
This is achieved byusing the ReAlloc() method:myRBuf.CleanupClosePushL();...const TInt newLength = myRBuf.Length() + appendBuf.Length();if (myRBuf.MaxLength() < newLength){myRBuf.ReAlloc(newLength);}myRBuf.Append(appendBuf);...CleanupStack::PopAndDestroy();// calls myRBuf.Close();If the ReAlloc() method is used on an HBufC object, the change inlocation of the heap cell means that any associated HBufC* and TPtrvariables need to be updated.
This update isn’t required for RBuf objects.A corresponding ReAllocL() method is available that acts similarlybut leaves on failure.DestructionRegardless of the way in which the buffer has been allocated, theRBuf object is responsible for freeing memory when the object itself isclosed. Both the Close() and the CleanupClosePushL() methodsare available and should be called appropriately. See the example forReAlloc() above.Other methodsWe have discussed the methods introduced in the RBuf class. Since RBufinherits from TDes, all the methods from TDes and TDesC are availableto RBuf and can be used as described in the Symbian Developer Librarydocumentation._LIT(KTextHello, "Hello");_LIT(KTextWorld, " World");RBuf myRBuf;myRBuf.CleanupClosePushL();myRBuf.CreateL(KHello());HEAP DESCRIPTORS107imyRBuf.ReAllocL(KHello().Length() + KWorld().Length());myRBuf.Append(KWorld);CleanupStack::PopAndDestroy() // calls myRBuf.Close();Migration from HBufCIt is desirable to migrate code that uses HBufC* and TPtr so that it usesjust RBuf.• It makes the code easier to read and understand and hence to maintain.• It reduces the possibility of errors.• The object code is slightly smaller as a TPtr doesn’t have to becreated around the object in order to modify it, as it does with anHBufC.Since it is possible to create an RBuf from an existing HBufC, it’seasy to move code over to this new class.
For example, when Symbianwas migrating code internally, the changes were mainly from code of theform:HBufC* mySocketName;...if(mySocketName==NULL){mySocketName = HBufC::NewL(KMaxName);}TPtr socketNamePtr (mySocketName->Des());aMessage.ReadL(aMessage.Ptr0(), socketNamePtr);// where aMessage is of type RMessage2to code like this:RBuf mySocketName;...if(mySocketName.IsNull()){mySocketName.CreateL(KMaxName);}aMessage.ReadL(aMessage.Ptr0(), mySocketName);An RBuf can directly replace an HBufC, so you can use it to callpredefined APIs that return HBufC s.
For example:HBufC* resString = iEikonEnv->AllocReadResourceLC (someResourceId);// increase size of label, copy old text and append new textlabelLength += 4;108DESCRIPTORSHBufC* label = HBufC::NewLC(labelLength);TPtr labelPtr(label->Des());labelPtr.Copy(*resString);labelPtr.Append(_L("-Foo"));//.
. . etc.SetLabelL(ELabel, *label);CleanupStack::PopAndDestroy(2);converts to:RBuf resString (iEikonEnv->AllocReadResourceL(someResourceId));resString.CleanupClosePushL();// Use modifiable descriptor to append new text. . .resString.ReAllocL(resString.Length() + 4);resString.Append(_L("-Foo"));//. . . etc.SetLabelL(ELabel, resString);CleanupStack::PopAndDestroy() // calls resString.Close();5.7 Narrow, Wide and Neutral DescriptorsSo far the descriptors we have seen are known as neutral descriptors.They are neutral in that their class names do not indicate if they storewide or narrow data.
There are actually two sets of descriptor classes: aset of narrow classes for storing 8-bit data and a set of wide classes forstoring 16-bit data. Their names end in either 8 or 16 to explicitly indicatewhat type of data they store, narrow or wide.If you specifically need to use narrow or wide data, you can usethe narrow or wide descriptor classes directly instead of the neutraldescriptors.So are the neutral descriptors wide or narrow? The answer is that theymay be either depending upon a compile-time flag. If you look in thee32std.h header file, you’ll be able to see the typedef s and the buildflag, the _UNICODE macro. Here is how it is done for TDesC and TBufC:#if defined(_UNICODE)typedef TDesC16 TDesC;#elsetypedef TDesC8 TDesC;#endiftemplate <TInt S>#ifdef _UNICODEclass TBufC : public TBufCBase16#elseclass TBufC : public TBufCBase8#endifHere is a list of the neutral, narrow and wide classes involved in thisscheme.DESCRIPTORS AND BINARY DATANeutralNarrowWide_LITTDesCTDesTPtrCTPtrTBufCTBufHBufCRBuf_LIT8TDesC8TDes8TPtrC8TPtr8TBufC8TBuf8HBufC8RBuf8_LIT16TDesC16TDes16TPtrC16TPtr16TBufC16TBuf16HBufC16RBuf16109You can find these definitions in e32def.h, e32std.h, e32des8.hand e32des16.h.Symbian OS was designed from the beginning to support worldwidelocales and although early versions used narrow 8-bit characters, itsarchitects planned for 16-bit characters from the beginning.
It was decidedto concentrate effort first on developing Symbian OS with narrow stringsand in the future it would be changed to deal with wide strings. Thetechnical foundation of the Symbian OS strategy was to program using theneutral versions of descriptors, then by simply changing the compilationflag, it would be possible to rebuild Symbian OS with 16-bit or 8-bitcharacters.Early versions of Symbian OS, up to and including v5.0, used narrowcharacters. The next version, v5.0U (the U stands for Unicode) andsubsequent versions used wide characters.