Skip to content

Commit 3e02b1d

Browse files
committed
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.
1 parent 9e78ab4 commit 3e02b1d

3 files changed

Lines changed: 42 additions & 3 deletions

File tree

py/nativeglue.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,14 @@ mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type) {
5050
case MP_NATIVE_TYPE_BOOL:
5151
case MP_NATIVE_TYPE_INT:
5252
case MP_NATIVE_TYPE_UINT: return mp_obj_get_int_truncated(obj);
53-
default: { // a pointer
53+
default: { // cast obj to a pointer
5454
mp_buffer_info_t bufinfo;
55-
mp_get_buffer_raise(obj, &bufinfo, MP_BUFFER_RW);
56-
return (mp_uint_t)bufinfo.buf;
55+
if (mp_get_buffer(obj, &bufinfo, MP_BUFFER_RW)) {
56+
return (mp_uint_t)bufinfo.buf;
57+
} else {
58+
// assume obj is an integer that represents an address
59+
return mp_obj_get_int_truncated(obj);
60+
}
5761
}
5862
}
5963
}

tests/micropython/viper_addr.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# test passing addresses to viper
2+
3+
@micropython.viper
4+
def get_addr(x:ptr) -> ptr:
5+
return x
6+
7+
@micropython.viper
8+
def memset(dest:ptr8, c:int, n:int):
9+
for i in range(n):
10+
dest[i] = c
11+
12+
# create array and get its address
13+
ar = bytearray('0000')
14+
addr = get_addr(ar)
15+
print(type(ar))
16+
print(type(addr))
17+
print(ar)
18+
19+
# pass array as an object
20+
memset(ar, ord('1'), len(ar))
21+
print(ar)
22+
23+
# pass direct pointer to array buffer
24+
memset(addr, ord('2'), len(ar))
25+
print(ar)
26+
27+
# pass direct pointer to array buffer, with offset
28+
memset(addr + 2, ord('3'), len(ar) - 2)
29+
print(ar)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<class 'bytearray'>
2+
<class 'int'>
3+
bytearray(b'0000')
4+
bytearray(b'1111')
5+
bytearray(b'2222')
6+
bytearray(b'2233')

0 commit comments

Comments
 (0)