Last active
January 8, 2021 22:46
-
-
Save sogaiu/a642f825fdf6d686aae4957eb45adf26 to your computer and use it in GitHub Desktop.
janet via python's ctypes
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 * | |
# macos may need .dylib | |
# windows may need WinDLL and .dll | |
dll = CDLL("./libjanet.so") | |
dll.janet_init() | |
# http://michas.eu/blog/c_ints.php?lang=en | |
# https://stackoverflow.com/a/13293860 | |
class Janet(Union): | |
_fields_ = [("u64", c_uint64), # uint64_t | |
("i64", c_int64), # int64_t | |
("number", c_double), | |
("pointer", c_void_p)] | |
class JanetKV(Structure): | |
_fields_ = [("key", Janet), | |
("value", Janet)] | |
# https://stackoverflow.com/a/1228447 | |
class JanetGCObject(Structure): | |
pass | |
JanetGCObject._fields_ = \ | |
[("flags", c_int32), | |
("next", POINTER(JanetGCObject))] | |
class JanetTable(Structure): | |
pass | |
JanetTable._fields_ = \ | |
[("gc", JanetGCObject), | |
("count", c_int32), | |
("capacity", c_int32), | |
("deleted", c_int32), | |
("data", POINTER(JanetKV)), | |
("proto", POINTER(JanetTable))] | |
# typedef const uint8_t *JanetSymbol; | |
# JANET_API JanetSymbol janet_symbol(const uint8_t *str, int32_t len); | |
dll.janet_symbol.restype = c_char_p | |
plus = dll.janet_symbol(c_char_p(bytes('+', "utf8")), 1) | |
dll.janet_core_env.restype = POINTER(JanetTable) | |
env = dll.janet_core_env(None) | |
env | |
env.contents | |
# JANET_API JanetKV *janet_table_find(JanetTable *t, Janet key); | |
dll.janet_table_find.restype = POINTER(JanetKV) | |
dll.janet_table_find(env, plus) | |
v = dll.janet_table_find(env, plus) | |
v.contents | |
v.contents.key | |
v.contents.value | |
dll.janet_dostring(env, c_char_p(bytes('(print "hi")', "utf8")), None, None) | |
out = Janet() | |
dll.janet_dostring(env, c_char_p(bytes('(+ 1 2)', "utf8")), None, byref(out)) | |
out | |
# 0 means number - see JanetType | |
dll.janet_type(out) | |
dll.janet_unwrap_number.restype = c_double | |
dll.janet_unwrap_number(out) | |
dll.janet_deinit() | |
# thanks to ahungry for: | |
# https://github.com/ahungry/puny-gui/blob/0f77f43b3adb88fd997e539c2daa1366602ad08d/app.c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment