如何将戈朗字符串添加到 cgo 中的 c 结构中

如何将 golang 字符串添加到我在 cgo 中制作的 c 结构中。代码如下:


package main


/*

#include <stdio.h>

#include <stdlib.h>

#include <errno.h>


typedef struct Point {

    int x, y;

} Point;


typedef struct Resp {

    char response;

} Resp;

*/

import "C"

import (

    "fmt"

    "io/ioutil"

    "unsafe"

)


type CPoint struct {

    Point C.Point

    Resp  C.Resp

}


func main() {


    var r string = "Hello World"

    resp := unsafe.Pointer(C.char(r))


    point := CPoint{

        Point: C.Point{x: 1, y: 2},

        Resp: C.Resp{response: resp},

    }

    fmt.Println(point)

}

但是每当我运行这个,我得到这个错误如何解决这个问题?如何通过 r 键入 _Ctype_char?cannot convert r (type string) to type _Ctype_char


另外,如何在 c 结构“Resp”中获取值?


package main


/*

#include <stdio.h>

#include <stdlib.h>

#include <errno.h>


typedef struct Point {

    int x, y;

} Point;


typedef struct Resp {

    char response; // <-- How can I get this value in my go code?

} Resp;

*/


30秒到达战场
浏览 65回答 1
1回答

森栏

您的代码需要 2 个修复:C 仅表示单个字符/字节 - 不表示字符串。C 字符串为 。charchar*您应该使用 从 Go 分配 C 字符串,并释放它。参见:https://pkg.go.dev/cmd/cgo#hdr-Go_references_to_C。C.CStringC.free以下是您使用这些修复程序的示例:package main// FIX: "char response" replaced with "char *response" below./*#include <stdio.h>#include <stdlib.h>#include <errno.h>typedef struct Point {&nbsp; &nbsp; int x, y;} Point;typedef struct Resp {&nbsp; &nbsp; char *response;} Resp;void fill(const char *name, Resp *r) {&nbsp; &nbsp;printf("name: %s\n", name);&nbsp; &nbsp;printf("Original value: %s\n", r->response);&nbsp; &nbsp;r->response = "testing";}*/import "C"import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "unsafe")// NOTE: You cannot pass this struct to C.// Types passed to C must be defined in C (eg, like "Point" above).type CPoint struct {&nbsp; &nbsp; Point C.Point&nbsp; &nbsp; Resp&nbsp; C.Resp}func main() {&nbsp; &nbsp; // FIX: Use CString to allocate a *C.char string.&nbsp; &nbsp; resp := C.CString("Hello World")&nbsp; &nbsp; point := CPoint{&nbsp; &nbsp; &nbsp; &nbsp; Point: C.Point{x: 1, y: 2},&nbsp; &nbsp; &nbsp; &nbsp; Resp:&nbsp; C.Resp{response: resp},&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(point)&nbsp; &nbsp; // Example of calling a C function and converting a C *char string to a Go string:&nbsp; &nbsp; cname := C.CString("foo")&nbsp; &nbsp; defer C.free(unsafe.Pointer(cname))&nbsp; &nbsp; r := &C.Resp{&nbsp; &nbsp; &nbsp; &nbsp; response: resp, // Use allocated C string.&nbsp; &nbsp; }&nbsp; &nbsp; C.fill(cname, r)&nbsp; &nbsp; goResp := C.GoString(r.response)&nbsp; &nbsp; fmt.Println(goResp)&nbsp; &nbsp; // FIX: Release manually allocated string with free(3) when no longer needed.&nbsp; &nbsp; C.free(unsafe.Pointer(resp))}
打开App,查看更多内容
随时随地看视频慕课网APP