Skip to content

Instantly share code, notes, and snippets.

@araraloren
Last active January 16, 2017 14:12
Show Gist options
  • Save araraloren/1ba08adbd6d8e8158b80fe86a639e993 to your computer and use it in GitHub Desktop.
Save araraloren/1ba08adbd6d8e8158b80fe86a639e993 to your computer and use it in GitHub Desktop.
perl6 nativecall with out parameters

We have a c source file: something.c

int xmode(char** str)
{
  (*str)[0] = 'X';
	(*str) ++; // xmode modified *str
	return 0;
}
  • version 3

sub xmode(CArray[Str] is rw) returns int32 is native('xmode') { * }

my CArray[Str] $astr .= new;

my $str = "54365";

explicitly-manage($str, encoding => 'utf8');

$astr[0] = $str;

explicitly-manage($astr[0]);

say $astr[0].perl; # "54365"

say xmode($astr);

refresh($astr[0]);

refresh($str);

say $astr[0].perl;  # "4365"

say $str; # "54365"
  • version 2

#!/usr/bin/env perl6

use v6;
use NativeCall;

sub xmode(CArray[CArray[uint8]]) returns int32 is native('xmode') { * }

my CArray[CArray[uint8]] $astr .= new;

$astr[0] = CArray[uint8].new("54365".encode.list);

say $astr[0].list.perl;	# (53, 52, 51, 54, 53)

say xmode($astr);

say $astr[0][0], $astr[0][1]; # 52 51
# say $astr[0].list; # a exception throwed : Don't know how many elements a C array returned from a library

So, how to get orignal string "X4654" in perl6 side .

  • version 1

Setup a perl6 file, use NativeCall call function xmode: something.p6

#!/usr/bin/env perl6

use v6;
use NativeCall;

sub xmode(CArray[Str]) returns int32 is native('xmode') { * }

my CArray[Str] $astr .= new;

$astr[0] = "54654";

say xmode($astr);

say $astr[0]; // rakudo output -> "4654"

So, how to get orignal string "X4654" in perl6 side .

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