From 3e02b1d19a4b1fb36ee36b0d43144bad6b797f2f Mon Sep 17 00:00:00 2001 From: Damien George Date: Tue, 9 Feb 2016 13:29:20 +0000 Subject: [PATCH] py/viper: Allow casting of Python integers to viper pointers. This allows you to pass a number (being an address) to a viper function that expects a pointer, and also allows casting of integers to pointers within viper functions. This was actually the original behaviour, but it regressed due to native type identifiers being promoted to 4 bits in width. --- py/nativeglue.c | 10 +++++++--- tests/micropython/viper_addr.py | 29 +++++++++++++++++++++++++++++ tests/micropython/viper_addr.py.exp | 6 ++++++ 3 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 tests/micropython/viper_addr.py create mode 100644 tests/micropython/viper_addr.py.exp diff --git a/py/nativeglue.c b/py/nativeglue.c index e27d69e14e..bc2f4ff5e7 100644 --- a/py/nativeglue.c +++ b/py/nativeglue.c @@ -50,10 +50,14 @@ mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type) { case MP_NATIVE_TYPE_BOOL: case MP_NATIVE_TYPE_INT: case MP_NATIVE_TYPE_UINT: return mp_obj_get_int_truncated(obj); - default: { // a pointer + default: { // cast obj to a pointer mp_buffer_info_t bufinfo; - mp_get_buffer_raise(obj, &bufinfo, MP_BUFFER_RW); - return (mp_uint_t)bufinfo.buf; + if (mp_get_buffer(obj, &bufinfo, MP_BUFFER_RW)) { + return (mp_uint_t)bufinfo.buf; + } else { + // assume obj is an integer that represents an address + return mp_obj_get_int_truncated(obj); + } } } } diff --git a/tests/micropython/viper_addr.py b/tests/micropython/viper_addr.py new file mode 100644 index 0000000000..cd953ce07d --- /dev/null +++ b/tests/micropython/viper_addr.py @@ -0,0 +1,29 @@ +# test passing addresses to viper + +@micropython.viper +def get_addr(x:ptr) -> ptr: + return x + +@micropython.viper +def memset(dest:ptr8, c:int, n:int): + for i in range(n): + dest[i] = c + +# create array and get its address +ar = bytearray('0000') +addr = get_addr(ar) +print(type(ar)) +print(type(addr)) +print(ar) + +# pass array as an object +memset(ar, ord('1'), len(ar)) +print(ar) + +# pass direct pointer to array buffer +memset(addr, ord('2'), len(ar)) +print(ar) + +# pass direct pointer to array buffer, with offset +memset(addr + 2, ord('3'), len(ar) - 2) +print(ar) diff --git a/tests/micropython/viper_addr.py.exp b/tests/micropython/viper_addr.py.exp new file mode 100644 index 0000000000..87a18e1e2a --- /dev/null +++ b/tests/micropython/viper_addr.py.exp @@ -0,0 +1,6 @@ + + +bytearray(b'0000') +bytearray(b'1111') +bytearray(b'2222') +bytearray(b'2233')