![](/img/trans.png)
[英]how to manipulate a pointer of char array (string) inside a function where it is passed as a parameter in c / c++
[英]How to manipulate a C character array inside a cgo function?
我有一個 C function,它正在調用一個帶有 char 數組參數的 go-Function。 go-Function 必須修改參數的內容。 如何做到這一點?
void cFunction() {
char buffer[9] = "aaabbbccc"; // 9 is in this case correct, it is not a null-terminated-string
goFunction(buffer);
// buffer shall be modified
}
func goFunction(cBuffer *C.char) {
// how to modify 3-5?
//strncpy(cBuffer+3, "XXX")
}
編輯:更准確地說。 我必須實現一個回調函數,它接受一個外參數,我必須對其進行操作。
void callback(char outbuffer[9]) {
goFunction(outbuffer);
}
據我了解弗蘭克斯的回答,我應該做類似的事情
allocate new go buffer
convert C buffer to go buffer
manipulate go buffer
allocate new C buffer
convert go buffer to C buffer
memcpy C buffer into outbuffer
這對我的口味來說太多的分配和轉換
See the documentation for Turning C arrays into Go slices to get a indexable go slice containing the C data.
因為您正在修改 C 緩沖區數據,使用 Go 切片作為代理,您可以簡單地將相同的緩沖區傳遞給回調。 請注意,使用append
可能會為您的切片分配一個新的 Go 數組,因此您需要避免它並確保事先在緩沖區中有足夠的可用空間。
func goFunction(cBuffer *C.char, length int) {
slice := (*[1 << 28]C.char)(unsafe.Pointer(cBuffer))[:length:length]
// slice can now be modified using Go syntax, without pointer arithmetic
C.callback(cBuffer)
}
不建議修改 Go 中的 C 結構,或 Z01250F83740143D4 中的 Go 結構。 在接口Ref1處轉換它。
一些特殊功能通過復制數據在 Go 和 C 類型之間進行轉換。 在偽 Go 定義中
更多,給你一種用零拷貝Ref2轉換字符串的方法。
func char2Slice(data unsafe.Pointer, len C.int) []byte {
var value []byte
sH := (*reflect.SliceHeader)(unsafe.Pointer(&value))
sH.Cap, sH.Len, sH.Data = int(len), int(len), uintptr(data)
return value
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.