Structures "on-the-fly"

Share your advanced PureBasic knowledge/code with the community.
User avatar
jqn
User
User
Posts: 97
Joined: Fri Oct 31, 2003 3:04 pm

Structures "on-the-fly"

Post by jqn »

Hi,
I dont know if this subject subject has been treated before. But if it serves for somebody:

Code: Select all

Structure mystruc
  mylong.l
  mystring.s
...
Endstructure


  *struc.mystruc  = Allocatememory(sizeof(mystruc))
  *struc\mylong   = sizeof(mystruc)
  *struc\mystring = "Loaded dato on the string..."
  ...

; At end you need to de-allocate string data
  *struc\mystring = ""
  Freememory(*struc)

It runs for my, but only few tests.

JOAQUIN
Xombie
Addict
Addict
Posts: 898
Joined: Thu Jul 01, 2004 2:51 am
Location: Tacoma, WA
Contact:

Post by Xombie »

Be careful here as I've run into a major problem with this in the past - using memory allocated structures and strings. See...

http://www.purebasic.fr/english/viewtopic.php?t=23099

... this posting for a solution from freak. Unless this behavior has changed in 4.01 beta for Windows and is now fixed.
Trond
Always Here
Always Here
Posts: 7446
Joined: Mon Sep 22, 2003 6:45 pm
Location: Norway

Post by Trond »

jqn's code will leak memory like a waterfall.
Xombie
Addict
Addict
Posts: 898
Joined: Thu Jul 01, 2004 2:51 am
Location: Tacoma, WA
Contact:

Post by Xombie »

I guess I should've added this originally to show the more correct method...

Code: Select all

Structure mystruc 
  mylong.l 
  mystring.s 
EndStructure 
;-
Procedure FreePBString(*Address) 
   ; Procedure and method of removing structure strings from memory from freak @ http://www.purebasic.fr/english/viewtopic.php?t=23099&start=0
   Protected String.String
   ; The String Structure contains one String element, which is initialized to 0 on procedure start 
   PokeL(@String, *Address)
   ; poke our strings address into the structure.  When returning, PB's string free routine for the local structure will actually free the passed string.
EndProcedure
;-
*struc.mystruc  = AllocateMemory(SizeOf(mystruc)) 
*struc\mylong   = SizeOf(mystruc) 
*struc\mystring = "Loaded dato on the string..." 
; At end you need to de-allocate string data 
FreePBString(@*struc\mystring)
;
FreeMemory(*struc) : *struc = 0
;-
End
;-
Konne
Enthusiast
Enthusiast
Posts: 434
Joined: Thu May 12, 2005 9:15 pm

Post by Konne »

Will FreeMemory work if I copy the String with CopyMemory and just save the Pointer as Pointer in the Structure?
I mean, it should...
Apart from that Mrs Lincoln, how was the show?
Post Reply