2 回答

TA貢獻1772條經(jīng)驗 獲得超8個贊
我終于可以String[]從GO使用中返回 a 了cgo。
我將留下函數(shù)簽名:
//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使用 創(chuàng)建結(jié)構(gòu)后cgo,Java我收到的數(shù)據(jù)如下:
IntByReference intByReference = new IntByReference();
PointerByReference array = lib.getSearchKeys(intByReference);
String[] results = array.getPointer().getStringArray(0, intByReference.getValue());
正如@PeterSO提到的,我們defer C.free()在使用它后進行了調(diào)用。否則,返回后將被釋放。

TA貢獻1863條經(jīng)驗 獲得超2個贊
你寫:
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
}
它可能執(zhí)行為:
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
?
Go 編程語言規(guī)范2019 年 7 月 31 日版本
推遲陳述
“defer”語句調(diào)用一個函數(shù),該函數(shù)的執(zhí)行被推遲到周圍函數(shù)返回的那一刻,要么是因為周圍函數(shù)執(zhí)行了 return 語句,到達了其函數(shù)體的末尾,要么是因為相應(yīng)的 goroutine 正在恐慌。
你寫:
set_char?:=?C.cmalloc(0) static?char**?cmalloc(int?size)?{ ????return?(char**)?malloc(size?*?sizeof(char*)); }
$ 人 malloc
malloc() 函數(shù)分配 size 字節(jié)并返回指向所分配內(nèi)存的指針。內(nèi)存未初始化。如果 size 為 0,則 malloc() 返回 NULL,或稍后可以成功傳遞給 free() 的唯一指針值。
為什么分配大小 0(零)?
malloc
內(nèi)存未初始化。
- 2 回答
- 0 關(guān)注
- 217 瀏覽
添加回答
舉報