SV * my_xs_func(p_struct, len) void *p_struct; IV len PREINIT: int bytes_read; char *tmp_buffer; PPCODE: tmp_buffer = (char *)malloc(len + 1); // + 1 for NULL if (tmp_buffer == NULL) XSRETURN_UNDEF; bytes_read = my_func(p_struct, tmp_buffer, len); // need to NULL-terminate the buffer tmp_buffer[bytes_read] = '\0'; XPUSHs(sv_2mortal(newSVpv(tmp_buffer, bytes_read))); free(tmp_buffer);