• Welcome to PlanetSquires Forums.
 

TIP: CWSTR - Dynamic unicode strings in UDTs

Started by José Roca, June 11, 2017, 03:17:08 PM

Previous topic - Next topic

José Roca

With CWSTR we can have dynamic unicode strings in an UDT.


   DIM _myudt AS MyUDT
   DIM cws1 AS CWSTR PTR = NEW CWSTR("First stting")
   DIM cws2 AS CWSTR PTR = NEW CWSTR("Second stting")
   _myudt.cws1 = cws1
   _myudt.cws2 = cws2

   print *_myudt.cws1
   print *_myudt.cws2

   *_myudt.cws1 = "qwerty"
   *_myudt.cws2 += " abcde"

   print *_myudt.cws1
   print *_myudt.cws2
   print MID(*_myudt.cws1, 3, 3)

   ' // Once finished, delete the CWSTR classes
   IF cws1 THEN Delete cws1
   IF cws2 THEN Delete cws2


José Roca

#1
If we don't use NEW, then we don't need to clean the memory used by the CWSTRins (the destructor of the class will dot it), but, of course, the pointer stored in the UDT won't we valid once a CWSTR goes out of scope.


TYPE MyUDT
   cws1 AS CWSTR PTR
   cws2 AS CWSTR PTR
END TYPE



   DIM _myudt AS MyUDT
   DIM cws1 AS CWSTR = "First stting"
   DIM cws2 AS CWSTR = "Second stting"
   _myudt.cws1 = @cws1
   _myudt.cws2 = @cws2

   print *_myudt.cws1
   print *_myudt.cws2

   *_myudt.cws1 = "qwerty"
   *_myudt.cws2 += " abcde"

   print *_myudt.cws1
   print *_myudt.cws2
   print MID(*_myudt.cws1, 3, 3)


Richard Kelly

Can you also do this with the dictionary object?

Rick

José Roca

#3
Of course.


TYPE MyUDT
   pDic AS CWstrDic PTR
END TYPE



   DIM _myudt AS MyUDT
   DIM pDic AS CWstrDic PTR = NEW CWstrDic

   ' // Adds some key, value pairs
   pDic->Add "a", "Athens"
   pDic->Add "b", "Belgrade"
   pDic->Add "c", "Cairo"

   ' // Assign the class pointer to the pDic member of the UDT
   _myudt.pDic = pDic
   ' // Number of items
   print "Count: "; _myudt.pDic->Count
   ' // Check if the key "a" exists
   print _myudt.pDic->Exists("a")
   ' // Change key "b" to "m" and "Belgrade" to "México"
   _myudt.pDic->Key("b") = "m"
   _myudt.pDic->Item("m") = "México"
   print _myudt.pDic->Item("m")
   ' --or--
   ' print pDic->Item("m")
   ' // Remove key "m"
   _myudt.pDic->Remove "m"
   IF _myudt.pDic->Exists("m") THEN PRINT "Key m exists" ELSE PRINT "Key m doesn't exists"

   ' // Once finished, delete the CwstrDic class
   IF pDic THEN Delete pDic


Also note that as both pDic and _myudt.pDic point to the same class, you can use both at the same time. And you can detele the class using Delete pDic or Delete _myudt.pDic, but don't delete the class twice!

Richard Kelly

This gives me some pause as multi dimensional arrays takes on a new meaning.

Rick