【问题标题】:how to copy go slice into c pointer如何将 go slice 复制到 c 指针中
【发布时间】: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 序言之后立即在线。请参阅cgo documentation 的第一部分
  • 对不起,基本的错误。现在更正了。

标签: c go cgo


【解决方案1】:

运行这个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)))
}

与:

GODEBUG=cgocheck=0 go run main.go

【讨论】:

  • go run main.go 导致恐慌错误恐慌:运行时错误:cgo 参数的 Go 指针指向 Go 指针 goroutine 1 [运行]:main.main.func1(0xc000030760) PRACTICE/GOLANG/sample。 go:29 +0x79 main.main() PRACTICE/GOLANG/sample.go:29 +0xc7 我不确定是否可以在生产代码中使用 cgocheck=0
猜你喜欢
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 2021-08-14
  • 2013-01-08
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多