Skip to content

Commit f20c081

Browse files
committed
Add PyMemoryView_FromMemory
1 parent a90d525 commit f20c081

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

graalpython/com.oracle.graal.python.cext/src/memoryobject.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,15 @@ PyObject* PyMemoryView_FromBuffer(Py_buffer *buffer) {
107107
buffer->suboffsets ? polyglot_from_size_array(buffer->suboffsets, ndim) : NULL);
108108
}
109109

110+
PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
111+
{
112+
assert(mem != NULL);
113+
assert(flags == PyBUF_READ || flags == PyBUF_WRITE);
114+
int readonly = (flags == PyBUF_WRITE) ? 0 : 1;
115+
return polyglot_invoke(PY_TRUFFLE_CEXT, "PyTruffle_MemoryViewFromBuffer",
116+
NULL, NULL, NULL, size, readonly, 1, polyglot_from_string("B", "ascii"), 1, polyglot_from_i8_array((int8_t*)mem, size), NULL, NULL, NULL);
117+
}
118+
110119
/* Macros taken from CPython */
111120
/* Memoryview buffer properties */
112121
#define MV_C_CONTIGUOUS(flags) (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C))

graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_memoryview.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,31 @@ def compile_module(self, name):
142142
cmpfunc=unhandled_error_compare_with_message,
143143
)
144144

145+
test_memoryview_frommemory = CPyExtFunction(
146+
lambda args: args[1],
147+
lambda: (
148+
(1, 50),
149+
(2, 60),
150+
(3, IndexError("index out of bounds on dimension 1"))
151+
),
152+
code='''
153+
char mem[] = {40, 50, 60};
154+
static PyObject* test_frommemory(PyObject *key, PyObject* expected) {
155+
PyObject *mv = PyMemoryView_FromMemory(mem, 3, PyBUF_READ);
156+
if (!mv)
157+
return NULL;
158+
PyObject *item = PyObject_GetItem(mv, key);
159+
Py_DECREF(mv);
160+
return item;
161+
}
162+
''',
163+
resultspec='O',
164+
argspec='OO',
165+
arguments=["PyObject* key", "PyObject* expected"],
166+
callfunction="test_frommemory",
167+
cmpfunc=unhandled_error_compare_with_message,
168+
)
169+
145170
test_memoryview_tolist = CPyExtFunction(
146171
lambda args: args[0],
147172
lambda: [

0 commit comments

Comments
 (0)