From caee076af8235c78d730e396bfb94fbe8e9777b2 Mon Sep 17 00:00:00 2001 From: mappu Date: Fri, 15 Nov 2024 15:09:29 +1300 Subject: [PATCH] genbindings/go: implement cabi type roundtrips for pointer types --- cmd/genbindings/emitcabi.go | 7 +++++++ cmd/genbindings/emitgo.go | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/cmd/genbindings/emitcabi.go b/cmd/genbindings/emitcabi.go index 325cdb09..b24e0af1 100644 --- a/cmd/genbindings/emitcabi.go +++ b/cmd/genbindings/emitcabi.go @@ -478,6 +478,13 @@ func emitAssignCppToCabi(assignExpression string, p CppParameter, rvalue string) } else if p.Const { shouldReturn += "(" + p.RenderTypeCabi() + ") " + } else { + // Basic type + if p.ByRef { + // The C++ type is a reference, the CABI type is a pointer type + shouldReturn += "&" + } + } return indent + shouldReturn + rvalue + ";\n" + afterCall diff --git a/cmd/genbindings/emitgo.go b/cmd/genbindings/emitgo.go index 3395f525..fc766e23 100644 --- a/cmd/genbindings/emitgo.go +++ b/cmd/genbindings/emitgo.go @@ -169,6 +169,11 @@ func (p CppParameter) parameterTypeCgo() string { return "C.struct_miqt_map" } + // Cgo internally binds void* as unsafe.Pointer{} + if p.ParameterType == "void" && p.Pointer { + return "unsafe.Pointer" + } + tmp := strings.Replace(p.RenderTypeCabi(), `*`, "", -1) if strings.HasPrefix(tmp, "const ") && tmp != "const char" { // Special typedef to make this work for const char* signal parameters @@ -542,6 +547,14 @@ func (gfs *goFileState) emitCabiToGo(assignExpr string, rt CppParameter, rvalue return shouldReturn + " " + rvalue + "\n" + afterword } else if rt.IntType() || rt.IsKnownEnum() || rt.IsFlagType() || rt.ParameterType == "bool" || rt.QtCppOriginalType != nil { + + if rt.Pointer || rt.ByRef { + // Cast must go via unsafe.Pointer + gfs.imports["unsafe"] = struct{}{} + return assignExpr + "(" + rt.RenderTypeGo(gfs) + ")(unsafe.Pointer(" + rvalue + "))\n" + + } + // Need to cast Cgo type to Go int type // Optimize assignment to avoid temporary return assignExpr + "(" + rt.RenderTypeGo(gfs) + ")(" + rvalue + ")\n"