【问题标题】:cgo Copy gobytes into c arraycgo 将 gobytes 复制到 c 数组中
【发布时间】:2021-04-10 17:07:47
【问题描述】:

我正在阅读 go 文档并尝试使用示例来完成主要要求。我花了很多时间在这个问题上,但无法解决这个问题。

在我的项目中,要求是将 go 字节数据复制到 C.char array[10] 中,这是一个 C 结构数据变量。我检查了 C.CBytes(),但这会创建新的内存。寻找类似于 copy()
下面是我尝试复制原始要求的示例代码。

package main
import "C"
/*
#include <stdio.h>
#include <string.h>
struct name {
 char fname[10];
 char lname[10];
};

struct infor{
   name ID[1];
   int id;
};

int receive(struct infor *c){
   printf("%s",c.ID.fname);
   printf("\n %s", c.id);
}
*/

type data struct {
        n [10]byte
        m [10]byte
}

func main(){
  d := data{}
  d.n = []byte("test1")
  d.m = []byte("test2")
  obj := C.struct_infor{}
  obj.ID.fname = d.n

}

【问题讨论】:

    标签: c go cgo


    【解决方案1】:

    您可以在string.h 中使用strcpy。以下是一个工作示例:

    package main
    
    /*
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct mystruct {
        char field[10];
    };
    
    */
    import "C"
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        x := new(C.struct_mystruct)
        bts := []byte("some text")
        C.strcpy((*C.char)(unsafe.Pointer(&x.field[0])), (*C.char)(unsafe.Pointer(&bts[0])))
        fmt.Printf("%#v", x)
    }
    

    重要的是,您必须获取第一个元素的不安全指针并将其转换为 *C.char 才能工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 2023-02-24
      • 2021-07-03
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多