|
| 1 | +from lpython import ccall, Pointer, i32, empty_c_void_p, CPtr, pointer |
| 2 | + |
| 3 | + |
| 4 | +@ccall(header="Python.h") |
| 5 | +def Py_Initialize(): |
| 6 | + pass |
| 7 | + |
| 8 | +@ccall(header="Python.h") |
| 9 | +def Py_DecodeLocale(s: str, p: CPtr) -> CPtr: |
| 10 | + pass |
| 11 | + |
| 12 | +@ccall(header="Python.h") |
| 13 | +def PySys_SetArgv(n: i32, args: Pointer[CPtr]): |
| 14 | + pass |
| 15 | + |
| 16 | +@ccall(header="Python.h") |
| 17 | +def Py_FinalizeEx() -> i32: |
| 18 | + pass |
| 19 | + |
| 20 | +@ccall(header="Python.h") |
| 21 | +def PyUnicode_FromString(s: str) -> CPtr: |
| 22 | + pass |
| 23 | + |
| 24 | +@ccall(header="Python.h") |
| 25 | +def PyImport_Import(name: CPtr) -> CPtr: |
| 26 | + pass |
| 27 | + |
| 28 | +@ccall(header="Python.h") |
| 29 | +def _Py_DecRef(name: CPtr): |
| 30 | + pass |
| 31 | + |
| 32 | +@ccall(header="Python.h") |
| 33 | +def PyObject_GetAttrString(m: CPtr, s: str) -> CPtr: |
| 34 | + pass |
| 35 | + |
| 36 | +@ccall(header="Python.h") |
| 37 | +def PyTuple_New(n: i32) -> CPtr: |
| 38 | + pass |
| 39 | + |
| 40 | +@ccall(header="Python.h") |
| 41 | +def PyObject_CallObject(a: CPtr, b: CPtr) -> CPtr: |
| 42 | + pass |
| 43 | + |
| 44 | +@ccall(header="Python.h") |
| 45 | +def PyLong_AsLongLong(a: CPtr) -> i32: |
| 46 | + pass |
| 47 | + |
| 48 | +def my_f(): |
| 49 | + pName: CPtr; pModule: CPtr; pFunc: CPtr; pArgs: CPtr; pValue: CPtr |
| 50 | + |
| 51 | + pName = PyUnicode_FromString("bindpy_05_module") |
| 52 | + assert pName != empty_c_void_p(), "Failed to convert to unicode string bindpy_05_module\n" |
| 53 | + |
| 54 | + pModule = PyImport_Import(pName) |
| 55 | + _Py_DecRef(pName) |
| 56 | + assert pModule != empty_c_void_p(), "Failed to load python module bindpy_05_module\n" |
| 57 | + |
| 58 | + pFunc = PyObject_GetAttrString(pModule, "my_f") |
| 59 | + assert pFunc != empty_c_void_p(), "Cannot find function my_f\n" |
| 60 | + |
| 61 | + pArgs = PyTuple_New(0) |
| 62 | + pValue = PyObject_CallObject(pFunc, pArgs) |
| 63 | + _Py_DecRef(pArgs) |
| 64 | + assert pValue != empty_c_void_p(), "Call to my_f failed\n" |
| 65 | + |
| 66 | + ans: i32 = PyLong_AsLongLong(pValue) |
| 67 | + print("Ans is", ans) |
| 68 | + assert ans == 5 |
| 69 | + |
| 70 | + |
| 71 | +def main0(): |
| 72 | + Py_Initialize() |
| 73 | + argv1: CPtr = Py_DecodeLocale("", empty_c_void_p()) |
| 74 | + PySys_SetArgv(1, pointer(argv1)) |
| 75 | + |
| 76 | + my_f() |
| 77 | + |
| 78 | + assert(Py_FinalizeEx() >= 0), "BindPython: Unknown Error in FinalizeEx()\n" |
| 79 | + |
| 80 | +main0() |
0 commit comments