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

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

從 go 更改 *C.char 的正確方法

從 go 更改 *C.char 的正確方法

Go
弒天下 2023-05-04 17:40:33
我是 go 和 cgo 的新手,在瀏覽互聯網一段時間后,我還沒有想出一種從 go 中更改 char* 的好而快速的方法。從 go& 更改 *C.char 的最快方法是什么這是我的代碼和我嘗試更改字符串的嘗試(它不起作用)package asciiEngine// #include <windows.h>import "C"type Screen struct {    Width, Height int    Length        C.ulong    Data          *C.char    GoData        string    HConsole      C.HANDLE    BytesWritten  C.DWORD    Start         C.COORD}func (s Screen) Draw() {    C.WriteConsoleOutputCharacter(s.HConsole, s.Data, s.Length, s.Start, &s.BytesWritten)}func CreateScreen(width, height int) Screen {    screen := Screen{        Width:        width,        Height:       height,        Length:       C.ulong(width * height),        Data:         (*C.char)(C.malloc(C.ulonglong(width * height))),        HConsole:     C.CreateConsoleScreenBuffer(C.GENERIC_READ|C.GENERIC_WRITE, 0, nil, C.CONSOLE_TEXTMODE_BUFFER, nil),        BytesWritten: 0,    }    screen.GoData = C.GoString(screen.Data) // my attempt to get a reference to the C string    //C.SetConsoleActiveScreenBuffer(screen.HConsole)    return screen}主要去:package main// #include "stdio.h"// void print(char* data) {//  printf(data);// }import "C"import (    "fmt"    "github.com/demantar/ascii-engine")func main() {    screen := asciiEngine.CreateScreen(100, 50)    C.print((*C.char)(screen.Data))    fmt.Println()    screen.GoData = "askdssdfselkkskdkflsekfjdkjfksjeflsdkfjjekdjflskasdfkksdjjekdskdfjkskd"    C.print((*C.char)(screen.Data))}輸出PP我對 C 也很陌生,我正在這樣做,因為我找不到一個庫來做這件事
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

例如,用作底層C數組的gDataGo切片引用。bytecDatachar


package main


import (

? ? "fmt"

? ? "unsafe"

)


/*

#include <stdlib.h>

#include <stdio.h>

#include <string.h>


int printData(unsigned char *data) {

? ? return printf("cData: %lu \"%s\"\n", (long unsigned int)strlen(data), data);

}

*/

import "C"


func main() {

? ? // Allocate C data buffer.

? ? width, height := 8, 2

? ? lenData := width * height

? ? // add string terminating null byte

? ? cData := (*C.uchar)(C.calloc(C.size_t(lenData+1), C.sizeof_uchar))


? ? // When no longer in use, free C allocations.

? ? defer C.free(unsafe.Pointer(cData))


? ? // Go slice reference to C data buffer,

? ? // minus string terminating null byte

? ? gData := (*[1 << 30]byte)(unsafe.Pointer(cData))[:lenData:lenData]


? ? // Write and read cData via gData.

? ? for i := range gData {

? ? ? ? gData[i] = '.'

? ? }

? ? copy(gData[0:], "Data")

? ? gData[len(gData)-1] = 'X'

? ? fmt.Printf("gData: %d %q\n", len(gData), gData)

? ? C.printData(cData)

}

輸出:


gData: 16 "Data...........X"

cData: 16 "Data...........X"


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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