将GOLang Structure的内容复制到C结构

时间:2017-11-20 11:19:20

标签: go cgo gccgo

我想将GOLang结构的内容复制到C Structure。 在这里,我希望将填充的GO Struct(类型测试结构)复制到C结构test_c。

已经提出以下逻辑。我在go文件中访问了C结构 test_c ,如 C.test_c ,并尝试将 test struct 的内容复制到C.test_c( p_c)通过使用C.GoString,但是当我尝试这样做时,我得到了这个错误

任何人都可以让我知道正在做的错误是什么,是否有更好的方法来实现同样的目标?

./go_structure.go:30: cannot use p_go.a (type string) as type *C.char in argument to _Cfunc_GoString
./go_structure.go:30: cannot use _Cfunc_GoString(p_go.a) (type string) as type [10]C.uchar in assignment
./go_structure.go:31: cannot use p_go.b (type string) as type *C.char in argument to _Cfunc_GoString
./go_structure.go:31: cannot use _Cfunc_GoString(p_go.b) (type string) as type [10]C.uchar in assignment

以下是代码,

  

go_stucture.go

package main

import (
    /*
        #include "cmain.h"
    */
    "C"
    "fmt"
    "unsafe"
)

type test struct {
    a string
    b string
}

func main() {

    var p_go test
    var p_c C.test_c
    p_go.a = "ABCDEFGHIJ"
    p_go.b = "QRSTUVXWYZ"

    //fmt.Println(unsafe.Sizeof(p_c.a))

    fmt.Println("In GO code\n")
    fmt.Println("GO code structure Member:a=%s", p_go.a)
    fmt.Println("GO code structure Member:b=%s", p_go.b)

    p_c.a = C.GoString(p_go.a)
    p_c.b = C.GoString(p_go.b)

    fmt.Println("Call C function by passing GO structure\n")
    C.cmain((*C.test_c)(unsafe.Pointer(&p_c)))
}
  

cmain.c

#include <stdio.h>
#include "cmain.h"
#include "_cgo_export.h"

void cmain(test_c *value) {
    printf("Inside C code\n");
    printf("C code structure Member:a=%s\n", value->a);
    printf("C code structure Member:b=%s\n", value->b);
}
  

cmain.h

typedef struct {
    unsigned char a[10];
    unsigned char b[10];
}test_c;
void cmain(test_c* value);

0 个答案:

没有答案