Ptr

From REALbasicWiki

Jump to: navigation, search

The Ptr datatype represents a pointer; that is, the memory address of a value. Its feature set was extended significantly in REALbasic 2006r2.



Contents

[edit] Comparing a Ptr to Nil

You can test whether a Ptr is nil (i.e. UInt32(p)= &h00000000) using the = or <> operators.

if p = nil then
if p <> nil then

Attempting to test a Ptr using the Is operator will result in a compile-time error.


[edit] Autoconversion to and from MemoryBlock

MemoryBlock supports conversion to and from Ptr. This makes it possible to pass MemoryBlocks to external functions and to get the address of a MemoryBlock.


[edit] Get the Address of a MemoryBlock

dim m as new MemoryBlock(1024)
dim p as Ptr = m


[edit] Passing MemoryBlocks to a Method With a Ptr Parameter

Consider the following function.

Sub Foo(p as Ptr)
  beep
End Sub


This code executes.

Foo nil

But this code results in a NilObjectException.

dim m as MemoryBlock = nil
Foo m

The reason is that conversion between MemoryBlock and Ptr is implemented using Operator_Convert methods. In the first code example, the compiler understands that a null pointer is supposed to be passed. In the second code example, the compiler inserts a call to MemoryBlock.Operator_Convert. Since m is nil, the result of the call is a NilObjectException.


[edit] Dereferencing To Obtain a Structure

Though not shown in autocomplete, for each structure defined in a project there is a corresponding accessor function available for Ptr. This accessor function takes an optional offset parameter. So, for example, suppose your project contains a structure CFRange. You can then write code like

dim r as CFRange = p.CFRange(0)

If p = nil, beware that the result will be a program crash, just as in an unmanaged language like C.


[edit] Getting and Setting CStrings

Ptr.CString(offset) allows you to get or set a CString. What happens is not the same as with a MemoryBlock, and this can trip up the unwary. The effect of the code

dim m as new MemoryBlock(4)
m.CString(0) = "foo"

is to copy the contents of the C string to the MemoryBlock.

The effect of this code

dim m as new MemoryBlock(4)
dim p as Ptr = m
p.CString(0) = "foo"

is to copy the address of the C string to the block of memory represented by m. That is, it is more or less the same as doing the following.

dim m as new MemoryBlock(4)
dim m2 as MemoryBlock = "foo"
m.Ptr(0) = m2
Personal tools
related