Pointers and memory access
To use a pointer, put * before the variable name. A pointer is a long variable which stores an address. It is generally associated with a structured type. So, you can access the structure via the pointer.
Example:*MyScreen.Screen = OpenScreen(0,320,200,8,0) mouseX = *MyScreen\MouseX ; Assuming than the Screen structure contains a MouseX fieldThere are only three valid methods to set the value of a pointer:
- Get the result from a function (as shown in the above example)
- Copy the value from another pointer
- Find the address of a variable, procedure or label (as shown below)
Note: Other than in C/C++ in PureBasic the * is always part of the variable name. Therefore *ptr and ptr are two different variables.
Addresses of variables
To find the address of a variable in your code, you use the at symbol (@). A common reason for using this is when you want to pass a structured type variable to a procedure. You must pass a pointer to this variable as you cannot pass structured variables directly.
Example:Structure astruct a.w b.l c.w EndStructure Procedure SetB(*myptr.astruct) *myptr\b = 69 EndProcedure If OpenConsole() DefType.astruct myvar myvar\b = 0 SetB( @myvar ) PrintN(Str(myvar\b)) Input() CloseConsole() EndIf End
Addresses of procedures
Normally only advanced programmers need to find the address of procedures. Probably the most common reason for needing the address of a procedure is when dealing with the OS at a low-level. Some OSes allow you to specify callback or hook functions (for some operations) which get called by the OS and allows the programmer to extend the ability of the OS routine. The address of a procedure is found in a similar way to variables.
Example:Procedure WindowCB(WindowID.l, Message.l, wParam.l, lParam.l) ; This is where the processing of your callback procedure would be performed EndProcedure ; A special callback for the Windows OS allowing you to process window events SetWindowCallback( @WindowCB() )
Addresses of labels
It can also be useful to find the address of labels in your code. This can be because you want to access the code or data stored at that label, or any other good reason you can think of. To find the address of a label, you put a question mark (?) in front of the label name.
Example:If OpenConsole() PrintN("Size of data file = " + Str(?endofmydata - ?mydata)) Input() CloseConsole() EndIf End DataSection mydata: IncludeBinary "somefile.bin" endofmydata: