Last active
December 17, 2023 08:02
-
-
Save richardkiss/4f1fc7e948ddb7e8dba1e9a907662073 to your computer and use it in GitHub Desktop.
Using ctypes in python to call a mojo function (mojo 0.6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ctypes import CFUNCTYPE, c_int | |
Ft = CFUNCTYPE(c_int, c_int, c_int) | |
def entry_point(ptr_to_function): | |
function_pointer = Ft(ptr_to_function) | |
result = function_pointer(5000, 2) | |
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
mojo build main.mojo | |
PYTHONPATH=$(pwd) ./main |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from memory.unsafe import Pointer | |
from python import Python | |
alias Ft = fn(Int, Int) -> Int | |
fn fn_ptr_as_int64(f: Ft) -> Int64: | |
"""Recast `f` to `Int64`.""" | |
var fcp = f | |
return Pointer[Ft].address_of(fcp).bitcast[Int64]()[0] | |
fn mojo_leaf(v: Int, w: Int) -> Int: | |
return 2001 + v * w | |
def main(): | |
let fn_ptr = fn_ptr_as_int64(mojo_leaf) | |
let ffi = Python.import_module("ffi") | |
entry_point = ffi.entry_point | |
print(entry_point(fn_ptr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment