go - 在 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 指针的方法?
解决方案
推荐阅读
- oop - 当存在第三方系统的限制时,使用哪种 OO 设计?
- ios - 使用 self.frame.width 时在不同模拟器中改变宽度
- reactjs - 在 ReactJS 中将数据映射到表
- css - 将鼠标悬停在菜单项上以突出显示 subnav 的背景
- python - 查找将模型连接到“直通”模型的字段
- vba - 不存在变量的默认值
- http - nginx - 向上游添加自定义标头
- docker - NewRelic 没有来自 docker mule 3.8.0 的数据报告
- c# - Json.NET 填充一个类,而不是另一个
- node.js - 如何在 Twilio 交互式语音系统中获取第三方数据?