Skip to content

Commit b0cdbde

Browse files
Thirumalai-Shaktivelcertik
authored andcommitted
Create an array using an API
1 parent 4996cf4 commit b0cdbde

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

src/runtime/lpython/lpython.py

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,18 @@ def get_data_type(t):
666666
else:
667667
return t + " "
668668

669+
def get_typenum(t):
670+
if t == "int":
671+
return "NPY_INT"
672+
elif t == "long int":
673+
return "NPY_LONG"
674+
elif t == "float":
675+
return "NPY_FLOAT"
676+
elif t == "double":
677+
return "NPY_DOUBLE"
678+
else:
679+
raise NotImplementedError("Type %s not implemented" % t)
680+
669681
self.fn_name = function.__name__
670682
# Get the source code of the function
671683
source_code = getsource(function)
@@ -793,12 +805,17 @@ def get_data_type(t):
793805
{self.fn_name}({pass_args}, &_{self.fn_name}_return_value[0]);
794806
795807
// Build and return the result as a Python object
796-
PyObject* list_obj = PyList_New({self.array_as_return_type[1][3]});
797-
for (int i = 0; i < {self.array_as_return_type[1][3]}; i++) {{
798-
PyObject* element = PyFloat_FromDouble(_{self.fn_name}_return_value->data[i]);
799-
PyList_SetItem(list_obj, i, element);
800-
}}
801-
return list_obj;"""
808+
{{
809+
npy_intp dims[] = {{{self.array_as_return_type[1][3]}}};
810+
PyObject* numpy_array = PyArray_SimpleNewFromData(1, dims, {
811+
get_typenum(self.array_as_return_type[1][2][:-2])},
812+
_{self.fn_name}_return_value->data);
813+
if (numpy_array == NULL) {{
814+
PyErr_SetString(PyExc_TypeError, "error creating an array");
815+
return NULL;
816+
}}
817+
return numpy_array;
818+
}}"""
802819
else:
803820
fill_return_details = f"""{self.fn_name}({pass_args});
804821
Py_RETURN_NONE;"""
@@ -890,8 +907,4 @@ def __call__(self, *args, **kwargs):
890907
# import the symbol from the shared library
891908
function = getattr(__import__("lpython_module_" + self.fn_name),
892909
self.fn_name)
893-
if self.array_as_return_type:
894-
from numpy import array
895-
return array(function(*args, **kwargs))
896-
else:
897-
return function(*args, **kwargs)
910+
return function(*args, **kwargs)

0 commit comments

Comments
 (0)