英文:
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() {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论