Union of Structures

Started by newdep, October 03, 2004, 08:20:28 AM

Previous topic - Next topic

newdep

Hello Lutz,



I hoped to figure it out myself but im unable to get the problem out...

Im trying to access different structures from a Union.

The Union contains xx structures. Somehow im unable get to the structure..



Perhpas you have a hint, using pack/unpack im able to get to the stucture

itself but not from within a Union.



Thanks in advance, Norman.
-- (define? (Cornflakes))

Lutz

#1
'unpack', 'get-integer' and 'get-char' all take memory (or string) addresses as an argument. You just need the memory address of you structure o union. Lets say you have the following in you library to import:



#include <stdio.h>

struct mystruct {
char * msg;
int intNumber;
double dFloat;
} data;

struct mystruct * foo(void)
{
data.msg = "hello";
data.intNumber = 123;
data.dFloat = 123.456;

return(&data);
}


Compile it to a library:



gcc test.c -lm -shared -o test.so

No import into newLISP:

> (import "./test.so" "foo")
foo <281A0554>

> (unpack "lu ld lf" (foo))
(672794072 123 123.456)

> (get-string 672794072) => "hello"


Note that in 'C' on a Linux PC 'char *' and 'int' are 32 bit and 'double' is a 64 bit float as used in newLISP. I used 'lu' to retrieve the pointer .



Sometimes a 'C' function takes a pointer to an existing memory area. In this case you just allocate memory in a string:

(set 'buff (dup "00" 10)) ;; 10 bytes of zeroed memory

and pass it to the function:

int foo(char * buff)
{
strcpy(buff, "hello");
return(0);
}

and from newLISP:

(foo buff)

buff => "hello"

All of the database modules like mysql.lsp, sqlite.lsp and osbd.lsp make heavily use of these techniques.



Lutz