I'm writing an XSUB to glue an existing C module to my perl code, but I'm kind of new to C.
I want to save 2 shorts and n unsigneds in a char * array (so I can return the array to the perl module and store it in a mysql table right away). I have looked into memcpy, but it doesn't seem to do what I want. This is what I am trying right now:
- short some_func() { ... }
-
unsigned some_other_func() { ... }
-
int n = 128;
-
-
char * return_func() {
-
char * result = malloc( sizeof( short ) * 2 + sizeof( unsigned ) * n );
-
int pos = 0;
-
short s = some_func();
-
memcpy( &result[pos], &s, sizeof(short) );
-
pos += sizeof(short);
-
s = some_func();
-
memcpy( &result[pos], &s, sizeof(short) );
-
pos += sizeof(short);
-
-
int i;
-
for( i=0; i<n; i++ ) {
-
unsigned u = some_other_func();
-
memcpy( &result[pos], &u, sizeof( unsigned ) );
-
pos += sizeof( unsigned );
-
}
-
-
return result;
-
}
Is there a better way to do this, without memcpy?
Or should i call memcpy in a different way?
Google couldn't help me out.
Thanks in advance.