Download Code Patterns in newLISP®

Transcript
Code Patterns in newLISP
astruc->number = num;
return(astruc);
}
The newLISP program would access the structure members as follows:
> (set ‘astruc (foo3 “hello world” 123))
4054280
> (get-string (get-integer (+ astruc 4)))
“hello world”
> (get-integer astruc)
123
>
The return value from foo3 is the address to the structure astruc. To access the string pointer,
4 must be added as the size of an integer type in the ‘C’ programming language. The string in the
string pointer then gets accessed using get-string.
Memory management
Any allocation performed by imported foreign functions has to be deallocated manually if there’s no
call in the imported API to do so. The libc function free can be imported and used to free memory
allocated inside imported functions:
(import “/usr/lib/libc.so” “free”)
(free astruc) ; astruc contains memory address of allocated structure
In case of calling foreign functions with passing by reference, memory for variables needs to be allocated beforehand by newLISP, and hence, memory needs not be deallocated manually.
Unevenly aligned structures
Sometimes data structures contain data types of different length than the normal CPU register word:
struct mystruct
{
short int x;
int z;
short int y;
} data;
struct mystruct * foo(void)
{
data.x = 123;
data.y = 456;
data.z = sizeof(data);
return(&data);
}
The x and y variables are 16 bit wide and only z takes 32 bit. When a compiler on a 32-bit CPU packs
this structure the variables x and y will each fill up 32 bits instead of the 16 bit each. This is necessary so the 32-bit variable z can be aligned properly. The following code would be necessary to access the structure members:
63