因此,我尝试通过动态加载在 C++ 项目上运行我的 go 代码。它工作得很好,除了返回值上有一些不需要的字符串。正如我解释的那样,我从 Go 那里得到了一些不需要的信息。
我的代码:
package main
import "C"
func main() {}
//export GetTestString
func GetTestString() string {
return "test"
}
我用以下方式构建它: go build -buildmode=c-shared -o test.so test.go
使用此功能将其动态加载到我的 CPP 项目中:
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..."
冉冉说
相关分类