wheezy-x64$ cat foo.i %module foo %{ // Fill the supplied buffer with data: void getBytes(unsigned char *buf, size_t len) { const unsigned char foo[] = {0xCA, 0xFE, 0xBA, 0xBE}; size_t i = 0; while ( len-- ) { *buf++ = foo[i++]; i &= 3; } } %} %typemap(in, numinputs=0) unsigned char * { // The uint8* parameter is created by the binding and adopted by Perl, not // passed in by the user. } %typemap(check) size_t { retVal = newSV(arg2); // allocate enough space sv_2mortal(retVal); // make it mortal sv_setpv(retVal, ""); // make it defined (i.e not undef) SvCUR_set(retVal, arg2); // set its length to its capacity arg1 = SvPVX(retVal); // get a raw uint8* pointing to its storage } %typemap(out) void getBytes(SV *retVal = NULL) { ST(argvi) = retVal; argvi++; } void getBytes(unsigned char *, size_t); wheezy-x64$ swig -perl5 foo.i wheezy-x64$ gcc -m64 -g -fPIC -Dbool=char -I/usr/lib/perl/5.14.2/CORE -I. -DLINUX=2 -D_REENTRANT -D_LARGEFILE64_SOURCE -shared foo_wrap.c -o foo.so wheezy-x64$ cat foo.pl #!/usr/bin/perl -w use foo; $bytes = foo::getBytes(16); print "Got ".length($bytes)." bytes:"; foreach ( unpack("(a1)*", $bytes) ) { print " ".sprintf("%02X", ord); } print "\n"; wheezy-x64$ ./foo.pl Got 16 bytes: CA FE BA BE CA FE BA BE CA FE BA BE CA FE BA BE wheezy-x64$