亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將戈朗字符串添加到 cgo 中的 c 結構中

如何將戈朗字符串添加到 cgo 中的 c 結構中

Go
30秒到達戰場 2022-10-04 16:13:19
如何將 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;*/
查看完整描述

1 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

您的代碼需要 2 個修復:

  1. C 僅表示單個字符/字節 - 不表示字符串。C 字符串為 。charchar*

  2. 您應該使用 從 Go 分配 C 字符串,并釋放它。參見:https://pkg.go.dev/cmd/cgo#hdr-Go_references_to_CC.CStringC.free

以下是您使用這些修復程序的示例:

package main


// FIX: "char response" replaced with "char *response" below.


/*

#include <stdio.h>

#include <stdlib.h>

#include <errno.h>


typedef struct Point {

    int x, y;

} Point;


typedef struct Resp {

    char *response;

} Resp;


void fill(const char *name, Resp *r) {

   printf("name: %s\n", name);

   printf("Original value: %s\n", r->response);

   r->response = "testing";

}

*/

import "C"

import (

    "fmt"

    "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 {

    Point C.Point

    Resp  C.Resp

}


func main() {

    // FIX: Use CString to allocate a *C.char string.

    resp := C.CString("Hello World")


    point := CPoint{

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

        Resp:  C.Resp{response: resp},

    }

    fmt.Println(point)


    // Example of calling a C function and converting a C *char string to a Go string:

    cname := C.CString("foo")

    defer C.free(unsafe.Pointer(cname))

    r := &C.Resp{

        response: resp, // Use allocated C string.

    }

    C.fill(cname, r)

    goResp := C.GoString(r.response)

    fmt.Println(goResp)


    // FIX: Release manually allocated string with free(3) when no longer needed.

    C.free(unsafe.Pointer(resp))

}


查看完整回答
反對 回復 2022-10-04
  • 1 回答
  • 0 關注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號