0

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

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

谁能让我知道正在做的错误是什么,有没有更好的方法来实现同样的错误?

./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

包主

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);
4

0 回答 0