Re: Pointer work around

new topic     » goto parent     » topic index » view thread      » older message » newer message

Paul Martin wrote:

> Since Euphoria does not handle pointers and structures like C
> does I was trying to find a simple solution that can be inserted,
> so that I would not have completely restructure the program and
> its data.

You probably want to map C structures into Euphoria sequences. Instead of
pointers, store the 'structures' in a global sequence, and pass the index
instead of a pointer. I typically name my global structure 'the'.

It help if you have some support functions to allocate/deallocate indexes in
the sequence. You can do this by setting up a parallel sequence which
contains a flag indicating if the sequence is free (untested code follows):

    sequence the, isFree
        the = {}
        isFree = {}

    function storeVal( object val )

        -- store a value into sequence 'the'
        -- return the index

        integer at

        -- look for a free slot
        at = find( -1, isFree )
        if at then
            -- store
            the[at]= val
            -- flag as taken
            isFree[at] = 0
            -- return index
            return at
        end if

        -- add an index
        the = append( the, value )
        -- add a flag
        isFree = append( isFree, 0 )
        -- return index
        return length( the )

    end function


    procedure freeVal( integer index )

        -- free value at index

        -- free the memory
        the[index] = 0
        -- flag the index as free
        isFree[index] = -1

    end procedure

The functions storeVal/freeVal roughly map into malloc/free.

The 'swap' function is typical example using pointers. In Euphoria (and C),
since parameters are treated as local, the following will *NOT* work:

    procedure swap( integer a, integer b )
        -- example of swap routine that *won't* work
        integer tmp
        tmp = a
        a = b
        b = tmp
    end procedure

Here is a version which uses indexes to the global sequence instead:

    procedure swap( integer first, integer second )
        -- swap two values in a global sequence
        integer tmp
        tmp = the[first]
        the[first] = the[second]
        the[second] = tmp
    end procedure


You could then do a swap like this:

    integer ptrA, ptrB

    -- allocate and store values in "addresses"
    ptrA = storeVal( 123 )
    ptrB = storeVal( 456 )

    -- swap values in "addresses"
    swap( ptrA, ptrB )

    -- display values in "addresses"
    ? the[ptrA]
    ? the[ptrB]

    -- free "addresses"
    freeVal( ptrA )
    freeVal( ptrB )


I find that 'the' as the name of the global sequence makes my code more
readable:

    the[creature][image] = bitmap12


Hope this helps.

-- David Cuny

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu