如何 return 来自 go 函数的 C 结构值

How to return a C struct value from a go function

我想 return 来自 Go 函数的 C 结构值。假设 ProcessX()ProcessY() 是 return 整数(uint8 值)的 go 方法:

package main

/*
struct Point {
    char x;
    char y;
};
*/

import "C"

//export CreatePoint
func CreatePoint(x uint8, y uint8) C.Point {
    xVal := ProcessX(x);
    yVal := ProcessY(y);
    return C.Point {x: xVal, y: yVal}
}

func main() {}

但这会导致构建错误:“.\main.go:13:36: could not determine kind of name for C.Point

编辑:

使用go build -ldflags "-s -w" -buildmode=c-shared -o mylibc.dll .\main.go通过mingw在Windows10中编译

编辑 2:

我已经删除了“C”导入和前面的序言之间的空行,但无法避免错误。现在的代码是这样的:

/*
struct Point {
    char x;
    char y;
};
*/
import "C"

我发现阅读文档有助于解决此类问题。

To access a struct type directly, prefix it with struct_, as in C.struct_stat.

cgo command

package main

/*
struct Point {
    char x;
    char y;
};
*/
import "C"

//export CreatePoint
func CreatePoint(x uint8, y uint8) C.struct_Point {
    xVal := ProcessX(x);
    yVal := ProcessY(y);
    return C.struct_Point {x: C.char(xVal), y: C.char(yVal)}
}

func ProcessX(x uint8) uint8 { return x | 'x'}
func ProcessY(y uint8) uint8 { return y | 'y'}

func main() {}