Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Support passing Bufs to Python
  • Loading branch information
niner committed Oct 14, 2014
1 parent cd96b59 commit a65b7df
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/Inline/Python.pm6
Expand Up @@ -55,6 +55,9 @@ sub py_string_to_buf(OpaquePointer, CArray[CArray[int8]])
sub py_str_to_py(Int, Str)
returns OpaquePointer { ... }
native(&py_str_to_py);
sub py_buf_to_py(Int, CArray[uint8])
returns OpaquePointer { ... }
native(&py_buf_to_py);
sub py_tuple_new(Int)
returns OpaquePointer { ... }
native(&py_tuple_new);
Expand Down Expand Up @@ -132,6 +135,14 @@ multi method p6_to_py(Str:D $value) returns OpaquePointer {
py_str_to_py($value.encode('UTF-8').bytes, $value);
}

multi method p6_to_py(blob8:D $value) returns OpaquePointer {
my $array = CArray[uint8].new();
for ^$value.elems {
$array[$_] = $value[$_];
}
py_buf_to_py($value.elems, $array);
}

method !setup_arguments(@args) {
my $len = @args.elems;
my $tuple = py_tuple_new($len);
Expand Down
4 changes: 4 additions & 0 deletions pyhelper.c
Expand Up @@ -72,6 +72,10 @@ PyObject *py_str_to_py(int len, char *str) {
return PyUnicode_DecodeUTF8(str, len, "replace");
}

PyObject *py_buf_to_py(int len, char *buf) {
return PyString_FromStringAndSize(buf, len);
}

char *py_unicode_to_char_star(PyObject *obj) {
PyObject * const string = PyUnicode_AsUTF8String(obj); /* new reference */
if (!string) {
Expand Down
45 changes: 45 additions & 0 deletions t/p6_to_py.t
@@ -0,0 +1,45 @@
#!/usr/bin/env perl6

use v6;
use Test;
use Inline::Python;

plan 4;

my $py = Inline::Python.new();
$py.run(q[
def identity(a):
return a
]);

class Foo {
}
# , 24, 2.4.Num, [1, 2], { a => 1, b => 2}, Any, Foo.new
for ('abcö', Buf.new('äbc'.encode('latin-1'))) -> $obj {
is_deeply $py.call('__main__', 'identity', $obj), $obj, "Can round-trip " ~ $obj.^name;
}

$py.run(q/
# coding=utf-8
def check_utf8(str):
return str == u'Töst'
/);

ok($py.call('__main__', 'check_utf8', 'Töst'), 'UTF-8 string recognized in Python');

$py.run(q/
# coding=utf-8
def check_latin1(str):
return str.decode('latin-1') == u'Töst';
/);

ok($py.call('__main__', 'check_latin1', 'Töst'.encode('latin-1')), 'latin-1 works in Python');

$py.run(q/
def is_two_point_five(a):
return a == 2.5;
/);

#ok($py.call('__main__', 'is_two_point_five', Num.new(2.5)));

# vim: ft=perl6

0 comments on commit a65b7df

Please sign in to comment.