如何在 cgo 导出函数中获取正确的参数名称?
How do I get proper parameter names in cgo exported functions?
我正在用 Go 编写一个库,我想导出到 c-shared-library。它工作得很好,但是我发现导出的 header 使用 p0
、p1
、p2
、...
作为参数名称而不是来自 Go 的原始参数名称。有没有办法改变这种行为,或者我只是坚持这样做?
I am using go version go1.12.7 darwin/amd64
示例:
package main
/*
#import <stdlib.h>
*/
import "C"
import (
"fmt"
)
func main() {}
//export MyFunc
func MyFunc(input *C.char) {
fmt.Println(C.GoString(input));
}
go build -o libout.so -buildmode=c-shared
输出:
extern void MyFunc(char* p0);
为什么 p0
没有命名为 input
?
根据 this cgo documentation,我应该得到变量名。
说明
Go functions can be exported for use by C code in the following way:
//export MyFunction
func MyFunction(arg1, arg2 int, arg3 string) int64 {...}
//export MyFunction2
func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
They will be available in the C code as:
extern int64 MyFunction(int arg1, int arg2, GoString arg3);
extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
然而,当我编译它给出的确切代码时,我得到了这个结果:
extern GoInt64 MyFunction(GoInt p0, GoInt p1, GoString p2);
extern struct MyFunction2_return MyFunction2(GoInt p0, GoInt p1, GoString p2);
为什么参数没有名字?
Go 允许任意符文名称,例如,您可以调用变量 π
而不是 input
。 C 不允许这样的名字。想必cgo的作者不想限制你的名字,所以他们只是重命名了所有东西。
奇怪的是,the documentation 暗示生成的代码将使用您的名字。如果它真的这样做了就好了,前提是你的名字是可行的。
我正在用 Go 编写一个库,我想导出到 c-shared-library。它工作得很好,但是我发现导出的 header 使用 p0
、p1
、p2
、...
作为参数名称而不是来自 Go 的原始参数名称。有没有办法改变这种行为,或者我只是坚持这样做?
I am using
go version go1.12.7 darwin/amd64
示例:
package main
/*
#import <stdlib.h>
*/
import "C"
import (
"fmt"
)
func main() {}
//export MyFunc
func MyFunc(input *C.char) {
fmt.Println(C.GoString(input));
}
go build -o libout.so -buildmode=c-shared
输出:
extern void MyFunc(char* p0);
为什么 p0
没有命名为 input
?
根据 this cgo documentation,我应该得到变量名。
说明
Go functions can be exported for use by C code in the following way:
//export MyFunction func MyFunction(arg1, arg2 int, arg3 string) int64 {...} //export MyFunction2 func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
They will be available in the C code as:
extern int64 MyFunction(int arg1, int arg2, GoString arg3); extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
然而,当我编译它给出的确切代码时,我得到了这个结果:
extern GoInt64 MyFunction(GoInt p0, GoInt p1, GoString p2);
extern struct MyFunction2_return MyFunction2(GoInt p0, GoInt p1, GoString p2);
为什么参数没有名字?
Go 允许任意符文名称,例如,您可以调用变量 π
而不是 input
。 C 不允许这样的名字。想必cgo的作者不想限制你的名字,所以他们只是重命名了所有东西。
奇怪的是,the documentation 暗示生成的代码将使用您的名字。如果它真的这样做了就好了,前提是你的名字是可行的。