Page 1 of 1

Structured Data 'New' and 'Delete'

Posted: Sat Mar 10, 2012 11:59 am
by Env
Hey all,

Find below some code that I use to create an allocator for structured data. It's a very simple concept, yet I've always found it useful, and with the latest revision being completed, I thought maybe someone here may also find it useful.

What does it do?

Very simply, say you want to have a more object-orientated approach to handling data, and wanted something a bit more than just AllocateMemory(SizeOf(...))... By using the macro 'mfwCreateAllocator(Structure)' it will generate code to create a constructor 'Structure_New()', and a destructor 'Structure_Delete(*Address)'... Not only that, you can optionally create procedures that will be called upon construction and destruction of the object.... Not only that!, you can also utilize LinkedLists to ensure all data allocated gets destroyed on application end by simply setting a constant.

The Code (Allocator.pbi)

Code: Select all

;------------------------------------------------------------------------------------------
; Title:        Allocator Library
; Description:  Macro to generate memory allocators for structured data object.
; Author(s):    Michael R. King (mrking2910@gmail.com)
; Revision:     10 March 2012
; Notes:        Part of the Mastiff Framework
;------------------------------------------------------------------------------------------

; - Allocation Mode -
CompilerIf Defined(MFW_ALLOC_USELIST, #PB_Constant) = #False
    #MFW_ALLOC_USELIST = #True      ; Set as True to enable allocations to be done using a LinkedList. (Prevent Memory Leaks)
CompilerEndIf

; - Allocator Macro -
Macro mfwCreateAllocator(Struct)
    CompilerIf #MFW_ALLOC_USELIST = #True
        Global NewList __mfwAllocator_#Struct.Struct()
    CompilerEndIf    
    Procedure.i Struct#_New()
        Protected *obj.Struct
        CompilerIf #MFW_ALLOC_USELIST = #True
            *obj = AddElement(__mfwAllocator_#Struct())
        CompilerElse
            *obj = AllocateMemory(SizeOf(Struct))
            InitializeStructure(*obj, Struct)
        CompilerEndIf
        CompilerIf Defined(Struct#_Constructor, #PB_Procedure)
            Struct#_Constructor(*obj)
        CompilerEndIf
        ProcedureReturn *obj
    EndProcedure    
    Procedure.a Struct#_Delete(*obj)
        If *obj
            CompilerIf Defined(Struct#_Destructor, #PB_Procedure)
                Struct#_Destructor(*obj)
            CompilerEndIf
            CompilerIf #MFW_ALLOC_USELIST = #True
                ForEach __mfwAllocator_#Struct()
                    If @__mfwAllocator_#Struct() = *obj
                        DeleteElement(__mfwAllocator_#Struct())
                        ProcedureReturn #True
                    EndIf
                Next
            CompilerElse
                FreeMemory(*obj)
                ProcedureReturn #True
            CompilerEndIf
        EndIf
        ProcedureReturn #False
    EndProcedure
EndMacro

; ----------------
; - Example Code -
; ----------------

; - Structure Definition -
Structure MyData
    SomeData.l
EndStructure

; - Constructor (Will be called upon allocating the object) -
Procedure MyData_Constructor(*this.MyData)
    Debug "Object has been allocated."
EndProcedure

; - Destructor (Will be called upon destroying the object) -
Procedure MyData_Destructor(*this.MyData)
    Debug "Object has been destroyed."
    Debug "SomeData = " + Str(*this\SomeData)
EndProcedure

; - Create Allocator -
mfwCreateAllocator(MyData)

; - Create Object -
Define.MyData *Object = MyData_New()

; - Assign Data -
*Object\SomeData = 1234

; - Destroy Object -
MyData_Delete(*Object)
Let me know what you think, and I hope someone else can find this useful.

Thanks!


EDIT: Changed the title of the thread to avoid confusion.

Re: Structured Data Allocation and Destruction

Posted: Sat Mar 10, 2012 12:28 pm
by Little John
Sorry, I don't understand what the advantage of your approach is, compared to simply writing

Code: Select all

Structure MyData
    SomeData.l
EndStructure

Define.MyData Object
Object\SomeData = 1234
Regards, Little John

Re: Structured Data Allocation and Destruction

Posted: Sat Mar 10, 2012 12:33 pm
by Env
It's more a foundation to be built upon, for instance, where scopes are a huge factor to take into consideration... Passing data around procedures, and across external libraries etc. It's mainly applicable to what I am working on, where merely defining the object in the main scope won't work.

As I said, it's there for people who would find it useful, and if the very basic method of doing it wont suffice.

Re: Structured Data Allocation and Destruction

Posted: Sat Mar 10, 2012 12:44 pm
by Little John
Env wrote:As I said, it's there for people who would find it useful,
People will find it useful if it is useful. ;-)
Env wrote:and if the very basic method of doing it wont suffice.
That was exactly my question: What is the advantage of your approach, compared to the simple standard approach? Can you give an example?

Regards, Little John

Re: Structured Data Allocation and Destruction

Posted: Sat Mar 10, 2012 12:56 pm
by Env
Well, one of the uses for my side things is dynamically creating objects, sending them across a modular tree of libraries, a very light-weight OOP paradigm.... etc. The example is a short example demonstrating what this piece of code does... not how it can be applied.

Anyone could say "Yeah, but I can do this... and this is easier." But your method wouldn't suit my needs, thus I developed this solution for what my project does need.

It's not forcing the standard on anyone, it's not saying "Define Something.Stuff" is incorrect... It's providing something for a developer who's needs outreach the very basic methods of handling variables/data if they can find use for it.
People will find it useful if it is useful.
I'll let each individual who see's this code decide for themselves if it's useful or not, and if it is, they can use it... I do apologies if I'm incorrect for assuming the above quote was an implication, but just because you can't find a use for something, doesn't render it useless for everyone.

P.S.. the concept of 'new' and 'delete' is already well known within C++, and languages similar... And are used widely across the spectrum of software development. Food for thought.

Re: Structured Data Allocation and Destruction

Posted: Sat Mar 10, 2012 6:32 pm
by Little John
Env wrote:The example is a short example demonstrating what this piece of code does... not how it can be applied.
And I asked for an example, that shows an advantage of your code compared to the simple standard approach. But it seems that you can't give such an example.
Env wrote:Anyone could say "Yeah, but I can do this... and this is easier." But your method wouldn't suit my needs, thus I developed this solution for what my project does need.
Sorry, if you post something in this "Tricks 'n' Tips" section, you shouldn' be surprised when someone asks what sense it makes not only for any of your personal projects, but for the rest of us.
Env wrote:It's not forcing the standard on anyone, it's not saying "Define Something.Stuff" is incorrect... It's providing something for a developer who's needs outreach the very basic methods of handling variables/data if they can find use for it.
Again you are claiming that your approach is more versatile or more powerful than the much more straight forward built-in standard approch, but although I repeatedly asked you to give examples or tell some facts that show any advantage of your approach, you do not do so. Your replies only contain unproven claims.
So I can only can draw the conclusion, that your approach does not have any advantage over the simple straight forward built-in way of doing it. That's just somewhat surprising for me, since the vast majority of "Tricks 'n' Tips" actually do have any advantages (which the respective author is able to explain).

Re: Structured Data 'New' and 'Delete'

Posted: Sat Mar 10, 2012 7:12 pm
by Env
Ok, to rise up to the provoking response...


Example 1:
Using OOP as an example using Interfaces accompanied by a structure to hold the data as well as a table of procedure addresses...

To briefly explain typical way of doing it, you create a constructor which allocates (using AllocateMemory(...) which I assume you also deem useless when it comes to anything other than peek and poke functions) memory for that instance of the object... Similar to C++'s 'MyClass *Instance = new MyClass();"... Problem with this can be it's often easy to lose allocations, especially when it comes to the more 'sloppy' coding habits we all sometimes fall into.... Lack of preventing memory leaks for instance.. so this option provides a way to switch from AllocateMemory(...) to using a LinkedList so that the memory allocated will be freed upon the executable terminating. Useful to check to see if memory leaks would occur if you were to switch back to raw memory allocation.

Example 2:
Dynamically allocating structured data - Yeah, you can use a linked list to do it, or an array, or a map... but if you're more than likely going to be passing that instance around, it could be considered useful to have some prefabricated code that instead of re-writing a list handler (if you were to use a LinkedList) for allocating and deallocating, you just have to pass your structure to the Macro which generates the code for you.

Example 3:
Now this is something I use it for: When I create windows in PureBasic, instead of using numeric ID's, I tend to have a template window constructor which constructs the window, gadgets, etc.. has all the event handlers, additional data, and so on encapsulated into a structure... You send the form structure (say 'MyForm') to the allocator, it manages the memory allocation and you can create procedures that will take the pointer, and manipulate the window for whatever purpose..

There's 3 very basic examples... Satisfied?, or should I dig around for my old pair of boxing gloves?

If you actually read what the first post says, it tells you pretty clearly what the piece of code does, so rather than just throw in a very arrogant chain of questioning, just take the decision of "Nope, doesn't suit my needs" and move on.

Re: Structured Data 'New' and 'Delete'

Posted: Sat Mar 10, 2012 8:41 pm
by Little John
Env wrote:Satisfied?, or should I dig around for my old pair of boxing gloves?

If you actually read what the first post says, it tells you pretty clearly what the piece of code does, so rather than just throw in a very arrogant chain of questioning, just take the decision of "Nope, doesn't suit my needs" and move on.
You did not understand most of what I wrote or preferred to ignore it. However, that's no reason to become abusive.

Re: Structured Data 'New' and 'Delete'

Posted: Mon Mar 12, 2012 5:56 am
by idle
looks ok to me, I can see it's uses

Re: Structured Data 'New' and 'Delete'

Posted: Fri Mar 16, 2012 8:46 pm
by Trond
Little John, this is an advanced version of AllocateMemory(). If you do not know why to use AllocateMemory() this thread is not the right place to explain it, as it assumes you're already familiar with why it's needed. Post in the coding questions section if you need information on AllocateMemory().

Edit: I see that sounded a bit harsh. I just got 50 mg of prednisolone.