Skip to content

Commit 36826cd

Browse files
committed
Fix the string encoding converted from Python string
1 parent e2a869f commit 36826cd

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

ext/pycall/pycall.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "pycall_internal.h"
2+
#include <ruby/encoding.h>
23

34
#include <stdarg.h>
45

@@ -1469,24 +1470,26 @@ pycall_pystring_to_ruby(PyObject *pyobj)
14691470
{
14701471
char *str = NULL;
14711472
Py_ssize_t len = 0;
1472-
int res = -1;
1473+
int encindex, res = -1;
14731474

14741475
/* TODO: PyUnicode_Check */
14751476
if (pyobj->ob_type == Py_API(PyUnicode_Type)) {
14761477
pyobj = Py_API(PyUnicode_AsUTF8String)(pyobj);
14771478
res = Py_API(PyString_AsStringAndSize)(pyobj, &str, &len);
1479+
encindex = rb_utf8_encindex();
14781480
pycall_Py_DecRef(pyobj);
14791481
}
14801482
/* TODO: PyString_Check */
14811483
else if (pyobj->ob_type == Py_API(PyString_Type)) {
14821484
res = Py_API(PyString_AsStringAndSize)(pyobj, &str, &len);
1485+
encindex = rb_ascii8bit_encindex();
14831486
}
14841487

14851488
if (res < 0) {
14861489
return Qnil;
14871490
}
14881491

1489-
return rb_str_new(str, len);
1492+
return rb_enc_str_new(str, len, rb_enc_from_index(encindex));
14901493
}
14911494

14921495
static VALUE

spec/pycall/conversion_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,13 @@ module PyCall
102102
it { is_expected.to be_a(Module) }
103103
it { is_expected.to be_a(PyObjectWrapper) }
104104
end
105+
106+
context 'for a unicode string' do
107+
let(:ruby_snowman) { "\u{2603}" }
108+
let(:python_snowman) { p Conversion.from_ruby(ruby_snowman) }
109+
subject { Conversion.to_ruby(python_snowman) }
110+
it { is_expected.to eq(ruby_snowman) }
111+
end
105112
end
106113

107114
describe '.from_ruby' do

0 commit comments

Comments
 (0)