Structures, memory and interfaces
Posted: Thu Oct 16, 2025 5:15 pm
Hi Guys,
I'm trying to achieve some kind of structure where i can access variables and methods at the same time. I got something similar using structure and prototype but i have to pass the pointer as a parameter on every method.
I read some messages explaining how to obtain the frame pointer thru asm, but you need to call the macro on every method, and i didn't like it too.
I came up with this mix, is it safe? I'm pretty new on working with purebasic and pointers, so i could be making some huge mistakes. The code works but i'm not sure about its safety.
I'm trying to achieve some kind of structure where i can access variables and methods at the same time. I got something similar using structure and prototype but i have to pass the pointer as a parameter on every method.
I read some messages explaining how to obtain the frame pointer thru asm, but you need to call the macro on every method, and i didn't like it too.
I came up with this mix, is it safe? I'm pretty new on working with purebasic and pointers, so i could be making some huge mistakes. The code works but i'm not sure about its safety.
Code: Select all
DeclareModule mcurrency
Structure st_base
*ptr_methods
text.s
value.i
EndStructure
Interface in_methods
mshow_text()
madd(vi.i)
EndInterface
Structure st_currency Extends mcurrency::st_base
methods.mcurrency::in_methods
EndStructure
Declare.i new(*ptr.st_currency)
Declare destroy(*ptr.st_currency)
EndDeclareModule
Module mcurrency
Procedure madd(*pst_currency.st_currency, vi.i)
*pst_currency\value = *pst_currency\value + vi
EndProcedure
Procedure mshow_text(*pst_currency.st_currency)
Debug "text: " + *pst_currency\text
EndProcedure
Procedure add_method(*pst_currency.st_currency, *ptr_adicionar)
Define vi_size.i
Define vi_size_add.i = SizeOf(*ptr_adicionar)
If *pst_currency\ptr_methods > 0
vi_size = MemorySize(*pst_currency\ptr_methods)
Else
vi_size = 0
EndIf
*pst_currency\ptr_methods = ReAllocateMemory(*pst_currency\ptr_methods, vi_size + vi_size_add, #PB_Memory_NoClear)
PokeI(*pst_currency\ptr_methods + vi_size, *ptr_adicionar)
EndProcedure
Procedure.i new(*pst_currency.st_currency)
Define *vst_currency.st_currency = AllocateStructure(st_currency)
*pst_currency = *vst_currency
*pst_currency\methods = *vst_currency
add_method(*vst_currency, @mshow_text())
add_method(*vst_currency, @madd())
ProcedureReturn *vst_currency
EndProcedure
Procedure destroy(*pst_currency.st_currency)
;Debug "destroying"
FreeMemory(*pst_currency\ptr_methods)
FreeStructure(*pst_currency)
ProcedureReturn 0
EndProcedure
EndModule
Define *vcurrency.mcurrency::st_currency
*vcurrency = mcurrency::new(*vcurrency)
*vcurrency\text = "this text will be displayed"
*vcurrency\methods\mshow_text()
*vcurrency\value = 1
*vcurrency\methods\madd(2)
Debug "it should be 3: " + *vcurrency\value
*vcurrency = mcurrency::destroy(*vcurrency)