Packing a multidimensional array

Started by Jeff, January 18, 2009, 02:33:43 PM

Previous topic - Next topic

Jeff

I need to create an array representing a series of string tuples, padding with a null between them. In c, it would be something like:


tuples[0] = "foo";
tuples[1] = "bar";
tuples[2] = NULL;


I tried the following in newlisp:


(setf packed (pack "s4 s4 s1" "foo" "bar" ""))

That did not, apparently, work... anyone know better than I?
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

Lutz

#1
actually is does work (if this is what you want?):



> (setf packed (pack "s4 s4 s1" "foo" "bar" ""))
"foo00bar0000"
>


but you could have that easier:


(setq packed "foo00bar0000") ; 3 digit decimals
(setq packed "foox00barx00x00") ; or 2 digit hex


are you sure you don't want an array of string pointers, like char * data[] or char ** data  (same)? Your: tuples[0] = "foo" ... example suggests, that it is what you want:


(setq packed (pack "lu lu lu" "foo" "bar" 0))

the third pointer in the array would be a NULL pointer, as usual in this kind of C array.



ps: look also here: http://www.newlisp.org/CodePatterns.html#extending">http://www.newlisp.org/CodePatterns.html#extending

last row in both tables at the end of the chapter



... forgot to mention:



make sure that your strings in newLISP are anchored to a fixed location, i.e:


(setq str-array '("foo" "bar" 0))
(set 'packed (pack "lu lu lu" str-array))

Jeff

#2
I thought that "lu lu lu" would coerce the strings into integers.  The case I am working toward is a function that requires parameters to be passed as an array of tuples (string * string), terminated with a NULL.  The documentation is here:



http://xmlsoft.org/xslt/html/libxslt-transform.html#xsltApplyStylesheet">http://xmlsoft.org/xslt/html/libxslt-tr ... Stylesheet">http://xmlsoft.org/xslt/html/libxslt-transform.html#xsltApplyStylesheet



I am trying to pass the params argument and construct it from an arbitrary association list.
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

Lutz

#3
those integers in:


(set 'packed (pack "lu lu lu" str-array))

will be taken as string pointers in the receiving function. The receiving function will take each of the three integers as a pointer to a string and check for NULL. When it hits the third, it knows that the end of the array is reached.


#include <stdio.h>

void showStrings(char * * params)
{
while(*params != NULL)
printf("->%sn", *params++);
}


compile on Mac OS X  (on Linux use -shared instead of -bundle and -o test.so):


gcc -bundle test.c -o test.dylib

and import and use:


> (import "test.dylib" "showStrings")
showStrings <AFFBE>
> (setq sarray '("foo" "bar" 0))
("foo" "bar" 0)
> (showStrings (pack "lu lu lu" sarray))
-> foo
-> bar
0
>


The last 0 is the return value from the function (void).