【发布时间】:2021-07-13 17:57:03
【问题描述】:
我需要将结构对象切片传递给 C 函数。 C 函数需要指向结构对象的指针 我关注了How to pass pointer to slice to C function in go。 我试图复制样本中的原始要求。在我得到的样本中
could not determine kind of name for C.f
我是 C 程序员,刚开始研究项目的 Go-module。有人可以更正下面的示例或提供示例以将 go slice 传递给 C 函数(C 代码采用指向结构的指针或双指针(任何合适的))
这是我的示例代码
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)
}
【问题讨论】:
-
“试图解决问题,但未能解决”不是问题陈述。究竟什么没有奏效,你期望会发生什么,你还尝试了什么?创建一个minimal reproducible example 显示您遇到的问题会有所帮助。
-
@JimB 我编辑了原帖
-
您的第一个错误是
import "C"必须在 C 序言之后立即在线。请参阅cgodocumentation 的第一部分 -
对不起,基本的错误。现在更正了。