Skip to content

Instantly share code, notes, and snippets.

@Altai-man
Last active January 9, 2016 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Altai-man/d2fb78521fe2eb62ae73 to your computer and use it in GitHub Desktop.
Save Altai-man/d2fb78521fe2eb62ae73 to your computer and use it in GitHub Desktop.
Native call expected return type with CArray representation, but got a VMArray
use v6;
use NativeCall;
# Needed bindings.
our sub fopen(Str $filename, Str $mode) returns OpaquePointer is
native() { ... }
our sub close(OpaquePointer $handle) is native() { ... }
# Bingings to bzip2(only needed parts).
our sub BZ2_bzWriteOpen(Pointer[int32], OpaquePointer, int32, int32, int32) returns OpaquePointer is native("/lib/libbz2.so.1") is export { * }
our sub BZ2_bzWrite(Pointer[int32], OpaquePointer, CArray[uint8], int32) is native("/lib/libbz2.so.1") is export { * }
# Code for testing.
my $text = CArray[uint8].new;
$text = "Test string.\n".encode;
my $filename = fopen("/tmp/test.bz2", "wb");
my $bzerror = Pointer[int32];
my $bz = BZ2_bzWriteOpen($bzerror, $filename, 1, 1, 0);
BZ2_bzWrite($bzerror, $bz, $text, 15); # Obviously error is here.
close($filename);
# C headers:
#BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( // It'll be just "BZ2_bzWriteOpen"
# int* bzerror,
# FILE* f,
# int blockSize100k,
# int verbosity,
# int workFactor
# );
#BZ_EXTERN void BZ_API(BZ2_bzWrite) (
# int* bzerror,
# BZFILE* b,
# void* buf,
# int len
# );
@jonathanstowe
Copy link

use v6;
use NativeCall;

# Needed bindings.
our sub fopen(Str $filename, Str $mode) returns OpaquePointer is native() { ... }
our sub close(OpaquePointer $handle) is native() { ... }

# Bingings to bzip2(only needed parts).
our sub BZ2_bzWriteOpen(int32 is rw, OpaquePointer, int32, int32, int32) returns OpaquePointer is native("bz2", v1) is export { * }
our sub BZ2_bzWrite(int32 is rw, OpaquePointer, CArray[uint8], int32) is native("bz2", v1) is export { * }

# Code for testing.

# You need to first encode the string to a Buf and then copy the
# element of the Buf to the new CArray
my $text = "Test string.\n";
my $t_buffer = $text.encode;
my $buff = CArray[uint8].new;
$buff[$_] = $t_buffer[$_] for ^$t_buffer.elems;
my $filename = fopen("/tmp/test.bz2", "wb");
my int32 $bzerror;
my $bz = BZ2_bzWriteOpen($bzerror, $filename, 1, 1, 0);
say $bzerror;

# use the length of the buffer as the length
BZ2_bzWrite($bzerror, $bz, $buff, $t_buffer.elems); # Obviously error is here.
say $bzerror;

close($filename);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment