如何从Go函数中返回一个C结构体值

huangapple go评论96阅读模式
英文:

How to return a C struct value from a go function

问题

我想从Go函数中返回一个C结构体值。假设ProcessX()ProcessY()是返回整数(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"

编辑:

在Windows 10上通过mingw使用go build -ldflags "-s -w" -buildmode=c-shared -o mylibc.dll .\main.go进行编译

编辑-2:

我已经删除了"C"导入和前面的前言之间的空行,但无法避免错误。现在的代码如下:

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

I want to return a C struct value from a Go function. Assuming ProcessX() and ProcessY() are go methods which return integers (uint8 values):

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() {}

But this results in a build error: ".\main.go:13:36: could not determine kind of name for C.Point"

Edit:

Using go build -ldflags "-s -w" -buildmode=c-shared -o mylibc.dll .\main.go to compile in Windows 10 through mingw

Edit-2:

I have removed the empty line between the "C" import and the preceeding preamble, but couldn't avoid the error. The code is now like:

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

答案1

得分: 1

我发现阅读文档对解决这类问题很有帮助。

> 要直接访问结构体类型,请在前面加上 struct_,例如 C.struct_stat。
>
> cgo 命令

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() {}
英文:

I find reading the documentation useful to solve problems like this.

> 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() {}

huangapple
  • 本文由 发表于 2022年5月10日 18:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/72184498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定