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