[]int32 を []byte に頻繁に変換するプロジェクトに取り組んでいます。コピーを最小限に抑えるためにインプレース変換を実行する関数 intsToBytes を作成しました。Go のエスケープ解析はそれを認識せず、同じ基になるデータints
を参照していることに気付きました。bytes
その結果、ints
次の関数のスタック データによって上書きされ、上書きされたデータbytes
を参照して存続します。
私が考えることができる唯一の解決策は、データを新しいバイト スライスにコピーすることです。データのコピーを避ける方法はありますか?
func pack() []byte {
ints := []int32{1,2,3,4,5} // This does not escape so it is allocated on the stack
bytes := intsToBytes(ints) // 'ints' and 'bytes' are different slice headers
return bytes
// After the return, the []int32{...} is deallocated and can be overwritten
// by the next function's stack data
}
func intsToBytes(i []int32) []byte {
const SizeOfInt32 = 4
// Get the slice header
header := *(*reflect.SliceHeader)(unsafe.Pointer(&i))
header.Len *= SizeOfInt32
header.Cap *= SizeOfInt32
// Convert slice header to an []byte
data := *(*[]byte)(unsafe.Pointer(&header))
/* Potentital Solution
outData := make([]byte, len(data))
copy(outData, data)
return outData
*/
return data
}