Skip to content

Commit

Permalink
get func name by runtime.FuncForPC
Browse files Browse the repository at this point in the history
  • Loading branch information
cpunion committed Oct 30, 2024
1 parent b1d1c72 commit a28cd3d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
2 changes: 1 addition & 1 deletion _demo/gradio/gradio.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
16 changes: 15 additions & 1 deletion function.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import "C"
import (
"fmt"
"reflect"
"runtime"
"strings"
"unsafe"
)

Expand Down Expand Up @@ -110,14 +112,26 @@ 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()
if t.Kind() != reflect.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{
Expand Down

0 comments on commit a28cd3d

Please sign in to comment.