Skip to content

Instantly share code, notes, and snippets.

@richardkiss
Last active December 17, 2023 08:02
Show Gist options
  • Save richardkiss/4f1fc7e948ddb7e8dba1e9a907662073 to your computer and use it in GitHub Desktop.
Save richardkiss/4f1fc7e948ddb7e8dba1e9a907662073 to your computer and use it in GitHub Desktop.
Using ctypes in python to call a mojo function (mojo 0.6)
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
#!/bin/sh
mojo build main.mojo
PYTHONPATH=$(pwd) ./main
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