doudi2229 2016-11-20 20:19
浏览 502
已采纳

是否需要C.GoBytes来检索C缓冲区,或者这里的指针是否足够?

The cgo code below has a function to put a Go value in a C buffer, and two alternative functions to get it back; getViaGoBytes and getDirect.

Is getViaGoBytes any better than getDirect?

I assume not, and the intermediary slice created in getViaGoBytes is unnecessary.

Am I correct in thinking Go allocates enough memory when the uint64 y variable is declared, and the assignment to y copies the memory from C to Go?

package main
/*
char buf[8];

void put(char * input, int size) {
    while (size--) {
        buf[size] = input[size];
    }
}
*/
import "C"
import "unsafe"

func put(input uint64) {
    C.put((*C.char)(unsafe.Pointer(&input)), C.int(unsafe.Sizeof(input)))
}

func getViaGoBytes() uint64 {
    var out uint64
    data := C.GoBytes(unsafe.Pointer(&(C.buf[0])), C.int(unsafe.Sizeof(out)))
    out = *(*uint64)(unsafe.Pointer(&data[0]))
    return out
}

func getDirect() uint64 {
    return *(*uint64)(unsafe.Pointer(&(C.buf[0])))
}

func main() {
    var input uint64 = 1<<64 - 1
    println(input)
    put(input)
    var x uint64 = getViaGoBytes()
    println(x)
    var y uint64 = getDirect()
    println(y)
}
  • 写回答

1条回答 默认 最新

  • dongliechuich10319 2016-12-03 17:52
    关注

    Marking question answered by copying JimB's answer from comment:

    GoBytes copies a C allocated buffer into a slice with Go allocated memory. If that's what you want, then use GoBytes. Here you're not even keeping that copy, so there's no reason to do it.

    Also, benchmark is interesting:

    $ go test -bench . -benchmem
    BenchmarkGoBytes-8      20000000            97.8 ns/op        32 B/op          3 allocs/op
    BenchmarkDirect-8       2000000000           0.84 ns/op        0 B/op          0 allocs/op
    PASS
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大