dpl9717 2015-10-20 00:31
浏览 130
已采纳

cgo如何在c中表示go类型?

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.

  • 写回答

1条回答 默认 最新

  • dqiz20794 2015-10-20 01:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器