From ee9a3ada7df0f0e074a929767bb1f222b911d312 Mon Sep 17 00:00:00 2001 From: topi314 Date: Sun, 24 Nov 2024 02:02:00 +0100 Subject: [PATCH] docs: add purego info --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 1b9833e..db0b8f0 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,30 @@ In the example above, to fetch the JavaScript grammar, you can run the following go get github.com/tree-sitter/tree-sitter-javascript@latest ``` +Alternatively you can also load grammars at runtime from a shared library via [purego](https://github.com/ebitengine/purego). + +This demonstrates how to load the JavaScript grammar from a shared library (`libtree-sitter-name.so`) at runtime on Linux & macOS: + +For more information on other platforms, see the [purego documentation](https://github.com/ebitengine/purego#supported-platforms) + +```go +package main + +import ( + tree_sitter "github.com/tree-sitter/go-tree-sitter" + "github.com/ebitengine/purego" +) + +func main() { + lib, err := purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_GLOBAL) + + var newLanguage func() uintptr + purego.RegisterLibFunc(&newLanguage, "libtree-siiter-javascript.so", "tree_sitter_javascript") + + language := tree_sitter.NewLanguage(unsafe.Pointer(newLanguage())) +} +``` + Due to [bugs with `runtime.SetFinalizer` and CGO](https://groups.google.com/g/golang-nuts/c/LIWj6Gl--es), you must always call `Close` on an object that allocates memory from C. This must be done for the `Parser`, `Tree`, `TreeCursor`, `Query`, `QueryCursor`, and `LookaheadIterator` objects.