首页 > 解决方案 > 在 Go 中使用 reflect.StringHeader 的安全性?

问题描述

我有一个小函数将 Go 字符串数据的指针传递给 C(Lua 库):

func (L *C.lua_State) pushLString(s string) {
    gostr := (*reflect.StringHeader)(unsafe.Pointer(&s))
    C.lua_pushlstring(L, (*C.char)(unsafe.Pointer(gostr.Data)), C.ulong(gostr.Len))
    // lua_pushlstring copies the given string, not keeping the original pointer.
}

它适用于简单的测试,但从文档中不清楚这是否安全。

根据Go 文档reflect.StringHeader应该为gostr固定内存,但Stringheader.Data它已经是一个uintptr没有指针语义的整数值” - 这本身很奇怪,因为如果它没有指针语义,那么该字段不会完全没用因为在读取值后可能会立即移动内存?还是该领域被特殊对待reflect.Value.Pointer?或者也许有另一种从字符串中获取 C 指针的方法?

标签: gocgo

解决方案


推荐阅读