Search code examples
gocgo

cgo how to represent go types in c?


when export go func to c, the interface type port to GoInterface, and int to GoInt. How to port my c funcs to go with these types?

a.h

void *SomeFunc(GoInterface arg);

a.c

void *SomeFunc(GoInterface arg) {
}

a.go

package main

// #include "a.h"
import "C"

type A struct {
}

func main() {
    var a = new(A)
}

when I go build:

cc errors for preamble:
In file included from ./a.go:3:0:
a.h:1:16: error: unknown type name 'GoInterface'
 void *SomeFunc(GoInterface arg)

Is there a header file for go like jni.h for java, So I can include there types.


Solution

  • No, Go doesn't have any way to export types as "C readable". Further, you cannot reference a Go struct from within C, and it is not safe to try and finagle a C struct to "look like" a Go struct since you have no control over memory layout.

    The "right" way to do this is to create a type in a C file and add it as a field in the Go struct:

    // from C
    typedef struct x {
        // fields
    } x;
    
    
    // From Go, include your .h file that defines this type.
    type X struct {
       c C.x
    }
    

    Then operate on your type that way, and pass C.x into all your C functions instead of x.

    There are a couple other ways, (for instance, converting between them any time you want to use it as one or the other), but this one is the best in a vague general sense.

    Edit: a FEW Go types can be represented in C, for instance, int64 will be defined in code that's compiled via cgo, but for the most part what I said holds.