鍍金池/ 問答/C  C++  GO/ golang如何實(shí)現(xiàn)內(nèi)存地址轉(zhuǎn)換為整數(shù),并傳遞到另一個函數(shù)還原回來???

golang如何實(shí)現(xiàn)內(nèi)存地址轉(zhuǎn)換為整數(shù),并傳遞到另一個函數(shù)還原回來???

go生成共享庫時不能導(dǎo)出復(fù)雜數(shù)據(jù)類型,我想把內(nèi)存地址轉(zhuǎn)換為整數(shù),導(dǎo)出,c使用的時候再把這個整數(shù)傳進(jìn)來,我再得到對象

回答
編輯回答
薄荷綠
//testgo.h
#ifdef __cplusplus
extern "C"{
#endif
extern long calladdr(long addr);
#ifdef __cplusplus
}
#endif
//testgo.cpp
#include "testgo.h"

long calladdr(long addr){
    return addr;
}
//test.go
package main

// #include "testgo.h"
// #cgo LDFLAGS: ${SRCDIR}/testgo.so -lstdc++
import "C"
import "fmt"
import "unsafe"

type Work struct {
    Name string
}

func main() {
    data := &Work{Name: "aaa"}
    ad := C.long(uintptr(unsafe.Pointer(data)))

    addr := C.calladdr(ad)
    newdata := (*Work)(unsafe.Pointer(uintptr(addr)))
    fmt.Println("newdata is", newdata)
}

應(yīng)該可以滿足要求

2017年1月3日 05:12