Using C-structs

Started by pjot, June 25, 2005, 04:59:28 PM

Previous topic - Next topic

pjot

Hi,



I browsed through old forum entries but I am unable to find the info back. Actually I'ld like to send a struct from newLisp to a C-library. E.g. this is the code:



typedef struct {
int i;
double d;
} MYSTRUCT;

void set_struct(MYSTRUCT n)
{
printf("number: %dn", n.i);
printf("string: %fn", n.d);
}

------------- newLisp code:

(import "./struct.so" "set_struct")
(set_struct (pack "ld lf" 1432 1.234))
(exit)


But this does not seem to work. How can I pass a reference to a complete structure to a C library?



Peter

pjot

#1
Never mind, I found the solution:



(import "./struct.so" "set_struct")
(set_struct 1432 1.234)
(exit)


It's too easy, really :-)



I was confused by this "Struct" - thing. Open mouth. Insert foot.

pjot

#2
Now I want to pass these 2 values at once:



(import "./struct.so" "set_struct")
(set 'VAR ....?.....)
(set_struct VAR)
(exit)


The VAR variable must contain an integer and a double value at te same time.



How can I define VAR in a way, that it contains 2 values each of which has a different type?



Peter

pjot

#3
Never mind again, I found it. Now I even can send information to an array of pointers of a struct type:



typedef struct {
char * ptr;
int i;
double d;
} MYSTRUC;

void set_struct(MYSTRUC *n[])
{
printf("string: %sn", n[0]->ptr);
printf("number: %dn", n[0]->i);
printf("float: %fn", n[0]->d);
printf("string: %sn", n[1]->ptr);
printf("number: %dn", n[1]->i);
printf("float: %fn", n[1]->d);
}

-----------------newLisp

(import "./struct.so" "set_struct")

(set 'txt1 "text")
(set 'var1 (pack "ld ld lf" (address txt1) 1234 4.321))

(set 'txt2 "letters")
(set 'var2 (pack "ld ld lf" (address txt2) 4567 7.654))

(set_struct (pack "ld ld" var1 var2))
(exit)


Quite complicated now but it works.



Peter

Lutz

#4
Just remember that sometimes fields inside a structure are not aligned the way you think. In your case you don't have a problem because all your fields have a size of 32bit or multiple of it (double float = 64 bits).



There is a chapter about all this in http://newlisp.org/DesignPatterns.html#libraries">http://newlisp.org/DesignPatterns.html#libraries



Lutz

pjot

#5
Thanks Lutz! I needed this stuff to create Drag and Drop with GTK. I posted the code here:



http://www.gtk-server.org/drag.lsp">http://www.gtk-server.org/drag.lsp



With the next release of the GTK-server (2.0.3) it is possible to implement Drag and Drop with GTK widgets as well.



For now, I will put the beta version of the GTK-server on the site.



Peter