mirror of
https://github.com/ralsina/tartrazine.git
synced 2025-06-18 22:23:07 -03:00
python: initial impl of bindings using cFFI
A PoC that exposes single function `enry.language_by_extension()` and a small number of helpers to deal with string coversion between Go<->C<->Python. Signed-off-by: Alexander Bezzubov <bzz@apache.org>
This commit is contained in:
40
python/enry.py
Normal file
40
python/enry.py
Normal file
@ -0,0 +1,40 @@
|
||||
"""
|
||||
Python library calling enry Go implementation trough cFFI (API, out-of-line) and Cgo.
|
||||
"""
|
||||
|
||||
from _c_enry import ffi, lib
|
||||
|
||||
|
||||
def go_str_to_py(go_str):
|
||||
str_len = go_str.n
|
||||
if str_len > 0:
|
||||
return ffi.unpack(go_str.p, go_str.n).decode()
|
||||
return ""
|
||||
|
||||
|
||||
def py_str_to_go(py_str):
|
||||
str_bytes = py_str.encode()
|
||||
c_str = ffi.new("char[]", str_bytes)
|
||||
go_str = ffi.new("_GoString_ *", [c_str, len(str_bytes)])
|
||||
return go_str[0]
|
||||
|
||||
|
||||
def language_by_extension(filename: str) -> str:
|
||||
fName = py_str_to_go(filename)
|
||||
guess = lib.GetLanguageByExtension(fName)
|
||||
lang = go_str_to_py(guess.r0)
|
||||
return lang
|
||||
|
||||
|
||||
## Test
|
||||
|
||||
|
||||
def main():
|
||||
files = ["Parse.hs", "some.cpp", "and.go", "type.h"]
|
||||
for filename in files:
|
||||
lang = language_by_extension(filename)
|
||||
print("file: {:10s} language: '{}'".format(filename, lang))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
Reference in New Issue
Block a user