From a28cd3d3e7f18449259782532e3e18037b6540a8 Mon Sep 17 00:00:00 2001 From: Li Jie Date: Wed, 30 Oct 2024 09:52:54 +0800 Subject: [PATCH] get func name by runtime.FuncForPC --- _demo/gradio/gradio.go | 2 +- function.go | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/_demo/gradio/gradio.go b/_demo/gradio/gradio.go index e236bee..8429d78 100644 --- a/_demo/gradio/gradio.go +++ b/_demo/gradio/gradio.go @@ -55,7 +55,7 @@ func main() { python.Initialize() gr = python.ImportModule("gradio") - fn := python.FuncOf("update_examples", UpdateExamples, + fn := python.FuncOf(UpdateExamples, "update_examples(country, /)\n--\n\nUpdate examples based on country") // fn := python.FuncOf1("update_examples", unsafe.Pointer(C.UpdateExamples2), // "update_examples(country, /)\n--\n\nUpdate examples based on country") diff --git a/function.go b/function.go index 22e2e41..b851b8a 100644 --- a/function.go +++ b/function.go @@ -11,6 +11,8 @@ import "C" import ( "fmt" "reflect" + "runtime" + "strings" "unsafe" ) @@ -110,7 +112,7 @@ func FuncOf1(name string, fn unsafe.Pointer, doc string) Func { return newFunc(pyFn) } -func FuncOf(name string, fn any, doc string) Func { +func FuncOf(fn any, doc string) Func { m := MainModule() v := reflect.ValueOf(fn) t := v.Type() @@ -118,6 +120,18 @@ func FuncOf(name string, fn any, doc string) Func { fmt.Printf("type: %T, kind: %d\n", fn, t.Kind()) panic("AddFunction: fn must be a function") } + + name := runtime.FuncForPC(v.Pointer()).Name() + if name == "" { + name = fmt.Sprintf("anonymous_func_%p", fn) + } else { + if idx := strings.LastIndex(name, "."); idx >= 0 { + name = name[idx+1:] + } + } + + doc = strings.ReplaceAll(doc, "update_examples", name) + ctx := &wrapperContext{v: fn, t: t} obj := C.PyCapsule_New(unsafe.Pointer(ctx), AllocCStr("wrapperContext"), nil) def := &C.PyMethodDef{