我想将数组返回给C调用者,如下所示,该怎么做?
//export EtcdGetAllNodes
func EtcdGetAllNodes()[]uint32 {
a := []uint32{1,2,3}
return a
}
此功能EtcdGetAllNodes
将尝试从etcd获取带有特定键前缀的值,它将返回多个值。如何将这些值返回给C调用者?
答案 0 :(得分:0)
由C代码调用的Go函数可能不会返回Go指针( 暗示它可能不返回字符串,切片,通道等 向前)。由C代码调用的Go函数可以将C指针用作 参数,它可以通过以下方式存储非指针或C指针数据: 这些指针,但它可能不会在指向的内存中存储Go指针 通过C指针。由C代码调用的Go函数可以使用Go指针 作为参数,但必须保留Go内存的属性 它指向的目标不包含任何Go指针。
我想将数组返回给C调用者。
//export EtcdGetAllNodes func EtcdGetAllNodes() []uint32 { a := []uint32{1, 2, 3} return a }
由C代码调用的Go函数可能不会返回Go指针(这意味着它可能不会返回切片)。
有许多可能的解决方案:Command 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: %d\n", *nodes);
for (uint32_t i = 1; i <= *nodes; i++) {
printf("node %d: %d\n", i-1,*(nodes+i));
}
free(nodes);
return 0;
}