[futurebasic] Re: [FB] malloc equivalent of PtrAndHand

Message: < previous - next > : Reply : Subscribe : Cleanse
Home   : December 2006 : Group Archive : Group : All Groups

From: Robert Purves <robert.purves@...>
Date: Thu, 14 Dec 2006 09:43:45 +1300
Bernie wrote:

> Apple say "Don't use NewPtr or NewHandle..." (TN2130). Any ideas  
> how to make a malloc equivalent of PtrAndHand?

The recommendation is for performance reasons, e.g. if you are  
allocating and deallocating thousands of blocks in time-critical  
code. Otherwise, continue to use Handles where convenient.

> (1) I managed to calculate the pointer size (see below) but then I  
> was immediately stumped because malloc sets the pointer size to the  
> next multiple of 16.

As you have discovered, malloc_size isn't much use for anything. You  
would have to keep track of the current size yourself, as in this  
(untested) code suite:

begin record PseudoHandle
dim as pointer p
dim as unsigned long usedBytes
end record

dim as PseudoHandle h

local fn NewPseudoHandle( h as PseudoHandle, size as unsigned long )
h.p = malloc( size )
h.usedBytes = size
end fn

local fn DisposePseudoHandle( h as PseudoHandle )
free( h.p )
end fn

local fn GetPseudoHandleSize( h as PseudoHandle )
end fn = h.usedBytes

local fn SetPseudoHandleSize( h as PseudoHandle, newSize as unsigned  
long )
realloc( h.p, newSize )
h.usedBytes = newSize
end fn

local fn PtrAndPseudoHand(...)
// left as exercise for the reader
end fn

> (2) An FB translation of malloc_size doesn't seem to exist in the  
> headers. I think this does the trick but should I be using a  
> different framework?
>
> '---------- malloc_size ----------
> local fn ApplicationServicesBundle
> '~'1
> begin globals
> dim as CFBundleRef  sApplicationServicesBundle// static
> end globals
> if ( sApplicationServicesBundle == 0 ) then  
> sApplicationServicesBundle = ¬
> fn CreateBundleForFramework( "ApplicationServices.framework" )
> end fn = sApplicationServicesBundle
>
> begin globals
> dim as pointer  gmalloc_size
> end globals
>
> gmalloc_size = fn GetMachFunctionFromBundle( ¬
> fn ApplicationServicesBundle(), "malloc_size" )
> local fn malloc_size( p as pointer )
> beginassem
>   lwz    r12,^gmalloc_size
>   mtspr  ctr,r12
>   mr     r31,r2
>   bctrl
>   mr     r2,r31
> endassem
> end fn// returns size_t (unsigned long?)
> '----------


Instead of fn ApplicationServicesBundle you can do this:

fn FBXInitBSDSystemFramework
gmalloc_size = fn GetMachFunctionFromBundle( gSysBundle, "malloc_size" )

Robert P.