Search code examples
gocgo

How do I get proper parameter names in cgo exported functions?


I'm writing a library in Go that I want to export to a c-shared-library. It works just fine, however i find it a little annoying that the exported header uses p0, p1, p2, ... for parameter names instead of the original parameter names from Go. Is there a way to change this behavior or am I simply stuck with that?

I am using go version go1.12.7 darwin/amd64

Example:

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

Output:

extern void MyFunc(char* p0);

Why isn't p0 named input?

According to this cgo documentation, i should be getting variable names.

It States

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);

However, when I compile that exact code it gave, i get this result:

extern GoInt64 MyFunction(GoInt p0, GoInt p1, GoString p2);
extern struct MyFunction2_return MyFunction2(GoInt p0, GoInt p1, GoString p2);

Why don't the parameters have their names?


Solution

  • Go allows arbitrary rune names, e.g., instead of input you might call the variable π. C does not allow such names. Presumably the cgo authors didn't want to restrict your names, so they just renamed everything.

    Curiously, the documentation implies that the generated code will use your names. It would be nice if it did do that, provided that your names are viable.