[英]how to copy go slice into c pointer
I need to pass slice of structure objects to C function.我需要将结构对象切片传递给 C function。 C function expects pointer to struct objects I followed How to pass pointer to slice to C function in go . C function expects pointer to struct objects I followed How to pass pointer to slice to C function in go . I tried to replicate the original requirement in sample.我试图复制样本中的原始要求。 In sample I am getting在我得到的样本中
could not determine kind of name for C.f
I am C programmer, just started working on Go-module of project.我是 C 程序员,刚开始研究项目的 Go 模块。 Can someone correct the below sample or provide a sample to pass go slice to C-function (C-code takes pointer to structure or double pointer (whatever is appropriate))有人可以更正下面的示例或提供示例以将 go 切片传递给 C 函数(C 代码采用指向结构的指针或双指针(无论是合适的))
here is my sample code这是我的示例代码
package main
/*
#include <stdio.h>
#include "cgoarray.h"
struct test {
int a;
int b;
};
int f(int c, struct test **s) {
int i;
printf("%d\n", c);
for (i = 0; i < c; i++) {
printf("%d\n", s[i].a);
}
c = (c) + 1;
return 1;
}
*/
import "C"
import "unsafe"
type struct gotest{
a int
b int
}
func go_f(harray ...gotest) {
count := len(harray)
c_count := C.int(count)
cArray :=(*C.struct_test)(C.malloc(C.size_t(c_count) *8));
// convert the C array to a Go Array so we can index it
a := (*[1<<30 - 1]*C.struct_test)(cArray)
for index, value := range harray {
a[index] = value
}
err := C.f(10, (**C.struct_test)(unsafe.Pointer(&cArray)))
return 0
}
func main(){
t :=gotest{10,20}
t1 :=gotest{30,40}
t2 :=gotest{50,60}
fmt.Println(t,t1,t2)
go_f(t1,t2,t3)
}
Run this main.go
:运行这个main.go
:
package main
/*
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a;
int b;
} Foo;
void pass_array(Foo **in, int len) {
for(int i = 0; i < len; i++) {
printf("A: %d\tB: %d\n", (*in+i)->a, (*in+i)->b);
}
}
*/
import "C"
import (
"unsafe"
)
type Foo struct{ a, b int32 }
func main() {
foos := []*Foo{{1, 2}, {3, 4}}
C.pass_array((**C.Foo)(unsafe.Pointer(&foos[0])), C.int(len(foos)))
}
With:和:
GODEBUG=cgocheck=0 go run main.go
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.