Created
May 7, 2023 01:35
-
-
Save mrcsparker/c88383538c11090ec1204019a46283fc to your computer and use it in GitHub Desktop.
Inline Rust for Python.
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
"""inline-rust. | |
Based on https://gist.github.com/adamnew123456/12546e6e36607a63e254 | |
Works with integers out-of-the-box. Other types not so much without work. | |
""" | |
import ctypes | |
import tempfile | |
import os | |
import atexit | |
class InlineRust: | |
compiler: str = "rustc" | |
def __init__(self, code: str) -> None: | |
self.code = code | |
def compile(self) -> ctypes.CDLL: | |
with tempfile.NamedTemporaryFile( | |
mode="w", prefix="PYC", suffix=".rs", delete=False | |
) as temp_c_file: | |
temp_c_file_name = temp_c_file.name | |
temp_c_file.write(self.code) | |
temp_c_file.flush() | |
obj_file_name = tempfile.mktemp(prefix="PYC", suffix=".dylib") | |
cmd = ( | |
f"{self.compiler} {temp_c_file_name} --crate-type cdylib -o {obj_file_name}" | |
) | |
os.system(cmd) | |
os.remove(temp_c_file_name) | |
atexit.register(lambda: os.remove(obj_file_name)) | |
return ctypes.cdll.LoadLibrary(obj_file_name) | |
def main() -> None: | |
code = """ | |
#[no_mangle] | |
pub extern "C" fn factorial(number: i64) -> i64 { | |
if number <= 1 { | |
return 1; | |
} | |
return number * factorial(number - 1); | |
} | |
""" | |
compiled = InlineRust(code).compile() | |
factorial = compiled["factorial"] | |
for i in range(10): | |
res = factorial(i) | |
print(res) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment