C 调用 Go 导出函数

  • 本文关键字:函数 Go 调用 c go cgo
  • 更新时间 :
  • 英文 :


我想将数组返回给 C 调用方,如下所示,该怎么做?

//export EtcdGetAllNodes
func EtcdGetAllNodes()[]uint32 {
a := []uint32{1,2,3}
return a
}

这个函数EtcdGetAllNodes尝试从 etcd 获取带有特定键前缀的值,它将返回多个值。如何将这些值返回给 C 调用方?

命令 cgo

传递指针

由 C 代码调用的 Go 函数可能不会返回 Go 指针(该指针 暗示它可能不会返回字符串、切片、通道等 四(。由 C 代码调用的 Go 函数可能将 C 指针作为 参数,并且它可以通过 那些指针,但它可能不会在内存中存储指向的 Go 指针 通过 C 指针。由 C 代码调用的 Go 函数可能采用 Go 指针 作为参数,但它必须保留 Go 内存的属性 它指向的不包含任何 Go 指针。


我想将数组返回给 C 调用方。

//export EtcdGetAllNodes
func EtcdGetAllNodes() []uint32 {
a := []uint32{1, 2, 3}
return a
}

C 代码调用的 Go 函数可能不会返回 Go 指针(这意味着它可能不会返回切片(。


有许多可能的解决方案:命令cgo。

例如,这里有一个简单的解决方案:

输出:

$ go build -buildmode=c-archive -o cmem.a cmem.go
$ gcc -pthread -o cmem cmem.c cmem.a
$ ./cmem
-- EtcdGetAllNodes --
nodes: 3
node 0: 1
node 1: 2
node 2: 3
$ echo $?
0
$ 

cmem.go

package main
/*
#include <stdint.h>
#include <stdlib.h>
*/
import "C"
import "unsafe"
// toC: Go slice to C array
// c[0] is the number of elements,
// c[1] through c[c[0]] are the elements.
// When no longer in use, free the C array.
func toC(a []uint32) *C.uint32_t {
// C array
ca := (*C.uint32_t)(C.calloc(C.size_t(1+len(a)), C.sizeof_uint32_t))
// Go slice of C array
ga := (*[1 << 30]uint32)(unsafe.Pointer(ca))[: 1+len(a) : 1+len(a)]
// number of elements
ga[0] = uint32(len(a))
// elements
for i, e := range a {
ga[1+i] = e
}
return ca
}
//export EtcdGetAllNodes
// EtcdGetAllNodes: return all nodes as a C array.
// nodes[0] is the number of node elements.
// nodes[1] through nodes[nodes[0]] are the node elements.
// When no longer in use, free the nodes array.
func EtcdGetAllNodes() *C.uint32_t {
// TODO: code to get all etcd nodes
a := []uint32{1, 2, 3}
// nodes as a C array
return toC(a)
}
func main() {}

cmem.c

#include "cmem.h"
#include <stdint.h>
#include <stdio.h>
int main() {
printf("-- EtcdGetAllNodes --n");
// nodes[0] is the number of node elements.
// nodes[1] through nodes[nodes[0]] are the node elements.
// When no longer in use, free the nodes array.
uint32_t *nodes = EtcdGetAllNodes();
if (!nodes) {
return 1;
}
printf("nodes: %dn", *nodes);
for (uint32_t i = 1; i <= *nodes; i++) {
printf("node %d: %dn", i-1,*(nodes+i));
}
free(nodes);
return 0;
}

最新更新