Union of Structures

Pondering the philosophy behind the language
Locked
newdep
Posts: 2038
Joined: Mon Feb 23, 2004 7:40 pm
Location: Netherlands

Union of Structures

Post by 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
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

'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:

Code: Select all

#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:

Code: Select all

gcc test.c -lm -shared -o test.so
No import into newLISP:

Code: Select all

> (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:

Code: Select all

(set 'buff (dup "\000" 10)) ;; 10 bytes of zeroed memory
and pass it to the function:

Code: Select all

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

Code: Select all

(foo buff)

buff => "hello"
All of the database modules like mysql.lsp, sqlite.lsp and osbd.lsp make heavily use of these techniques.

Lutz

Locked