diff --git a/src/js2python.c b/src/js2python.c index 520e57c94..a61bf76e1 100644 --- a/src/js2python.c +++ b/src/js2python.c @@ -49,9 +49,15 @@ _js2python_pyproxy(PyObject* val) } int -_js2python_bytes(char* bytes, int length) +_js2python_init_bytes(int length) { - return (int)PyBytes_FromStringAndSize(bytes, length); + return (int)PyBytes_FromStringAndSize(NULL, length); +} + +int +_js2python_get_bytes_ptr(PyObject* val) +{ + return (int)PyBytes_AsString(val); } int @@ -82,9 +88,9 @@ EM_JS(int, __js2python, (int id), { } else if (Module.PyProxy.isPyProxy(value)) { return __js2python_pyproxy(Module.PyProxy.getPtr(value)); } else if (value['byteLength'] !== undefined) { - var bytes = allocate(value, 'i8', ALLOC_NORMAL); - var result = __js2python_bytes(bytes, value['byteLength']); - _free(bytes); + var result = __js2python_init_bytes(value['byteLength']); + var ptr = __js2python_get_bytes_ptr(result); + Module.HEAPU8.set(new Uint8Array(value.buffer), ptr); return result; } else { return __js2python_jsproxy(id); diff --git a/test/test_python.py b/test/test_python.py index fd30db8cb..ae8c64f27 100644 --- a/test/test_python.py +++ b/test/test_python.py @@ -67,6 +67,7 @@ def test_js2python(selenium): 'window.jsfalse = false;\n' 'window.jspython = pyodide.pyimport("open");\n' 'window.jsbytes = new Uint8Array([1, 2, 3]);\n' + 'window.jsfloats = new Float32Array([1, 2, 3]);\n' 'window.jsobject = new XMLHttpRequest();\n' ) assert selenium.run( @@ -93,6 +94,12 @@ def test_js2python(selenium): assert selenium.run( 'from js import jsbytes\n' 'jsbytes == b"\x01\x02\x03"') + assert selenium.run( + 'from js import jsfloats\n' + 'print(jsfloats)\n' + 'import struct\n' + 'expected = struct.pack("fff", 1, 2, 3)\n' + 'jsfloats == expected') assert selenium.run( 'from js import jsobject\n' 'str(jsobject) == "[object XMLHttpRequest]"')