2 回答

TA貢獻1820條經驗 獲得超2個贊
我終于可以String[]從GOusing中返回 a 了cgo。
我將留下函數簽名:
//export getSearchKeys
func getSearchKeys(numKeysByReference *C.int) **C.char {
*numKeysByReference = // ... some value
// Using the C helper defined above
set_char := C.cmalloc(*numKeysByReference)
// Logic allocating and populating C.char[i .. *numKeysByReference]
// ...
return set_char
}
在使用,創建**C.char結構后,我收到如下數據:cgoJava
IntByReference intByReference = new IntByReference();
PointerByReference array = lib.getSearchKeys(intByReference);
String[] results = array.getPointer().getStringArray(0, intByReference.getValue());
正如@PeterSO 提到的,我們defer C.free()在使用它后打電話。否則,它會在返回后被釋放。

TA貢獻1799條經驗 獲得超6個贊
你寫:
func getSearchKeysA() **C.char {
set_char := C.cmalloc(0)
defer C.free(unsafe.Pointer(set_char))
C.setElement(set_char, C.CString("hello world"), C.int(0))
return set_char
}
這可能執行為:
func getSearchKeysA() (retval **C.char) {
set_char := C.cmalloc(42)
C.setElement(set_char, C.CString("hello world"), C.int(1))
retval = set_char
C.free(unsafe.Pointer(set_char))
return retval
}
你是指set_char之后free嗎?
2019 年 7 月 31 日的 Go 編程語言規范版本
延遲語句
“defer”語句調用一個函數,該函數的執行被推遲到周圍函數返回的那一刻,要么是因為周圍函數執行了一個 return 語句,到達了它的函數體的末尾,要么是因為相應的 goroutine 正在恐慌。
你寫:
set_char := C.cmalloc(0)
static char** cmalloc(int size) {
return (char**) malloc(size * sizeof(char*));
}
$ 人 malloc
malloc() 函數分配 size 個字節并返回一個指向已分配內存的指針。內存未初始化。如果 size 為 0,則 malloc() 返回 NULL 或稍后可以成功傳遞給 free() 的唯一指針值。
為什么分配大小 0(零)?
malloc內存未初始化。
- 2 回答
- 0 關注
- 367 瀏覽
添加回答
舉報