第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

從動(dòng)態(tài)加載的 Golang 到 CPP 的未知字符串

從動(dòng)態(tài)加載的 Golang 到 CPP 的未知字符串

Go
慕容708150 2022-10-17 17:14:33
因此,我嘗試通過動(dòng)態(tài)加載在 C++ 項(xiàng)目上運(yùn)行我的 go 代碼。它工作得很好,除了返回值上有一些不需要的字符串。正如我解釋的那樣,我從 Go 那里得到了一些不需要的信息。我的代碼:package mainimport "C"func main() {}//export GetTestStringfunc GetTestString() string {    return "test"}我用以下方式構(gòu)建它: go build -buildmode=c-shared -o test.so test.go使用此功能將其動(dòng)態(tài)加載到我的 CPP 項(xiàng)目中:typedef struct { const char *p; ptrdiff_t n; } GoString;void getTestString() {    void *handle;    char *error;    handle = dlopen ("./test.so", RTLD_LAZY);    if (!handle) {        fputs (dlerror(), stderr);        exit(1);    }    // resolve getTestString symbol and assign to fn ptr    auto getTestString = (GoString (*)())dlsym(handle, "GetTestString");    if ((error = dlerror()) != NULL)  {        fputs(error, stderr);        exit(1);    }    // call GetTestString()    GoString testString = (*getTestString)();    printf("%s\n", testString.p);    // close file handle when done    dlclose(handle);}輸出是:" test true ...\n H_T= H_a= H_g= MB, W_a= and cnt= h_a= h_g= h_t= max= ptr siz= tab= top= u_a= u_g=, ..., fp:argp=falsefaultgcingpanicsleepsse41sse42ssse3 (MB)\n addr= base code= ctxt: curg= goid jobs= list= m->p= next= p->m= prev= span= varp=(...)\n, 不是 SCHED efenceerrno objectpopcntscvg: selectsweep (scan (scan) MB in Dying= locks= m->g0= nmsys= s=nil\n, goid=, size=, sys: GODEBUGIO waitSignal \ttypes \tvalue=cs fs gctracegs panic: r10 r11 r12 r13 r14 r15 r8 r9 rax rbp rbx rcx rdi rdx rflags rip rsi rsp runningsignal syscallunknownwaiting etypes goalΔ= is not mcount= minutes nalloc= newval= nfree..."
查看完整描述

1 回答

?
冉冉說

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊

通過指向 C 的指針傳遞字符串時(shí),您需要使用 length ( n) inGoString來獲取正確數(shù)量的字符,因?yàn)樽址?atp未\0終止?;蛘吣梢苑祷?C.char而不是string使用C.CString()在 C 堆上分配副本(然后您負(fù)責(zé)在使用后釋放)。請(qǐng)參閱此處的Cgo 文檔。


您的代碼中發(fā)生的事情是printf()簡(jiǎn)單地打印從指向的位置開始的所有字符,string.p直到它到達(dá)\0終止符 - 這就是為什么您在test.


因此,您可以執(zhí)行以下任一操作:


printf("%.*s\n", testString.n, testString.p);

(但請(qǐng)注意,大多數(shù)對(duì)預(yù)期\0終止的 C 字符串進(jìn)行操作的函數(shù)將無法在此指針上工作,除非它們也占用字符串的長(zhǎng)度)


或?qū)?Go 部分更改為這樣的內(nèi)容,然后free()在 C 端使用后使用指針:


func GetTestString() *C.char {

    return C.CString("test") // CString will allocate string on C heap

}


查看完整回答
反對(duì) 回復(fù) 2022-10-17
  • 1 回答
  • 0 關(guān)注
  • 122 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)