登录
首页 >  Golang >  Go问答

在Golang中如何将 void* 转换为特定类型

来源:stackoverflow

时间:2024-03-15 23:06:31 414浏览 收藏

在 Go 语言中,无法直接将 void* 转换为特定类型,因为 Go 语言的内存模型与 C++ 不同。在 C++ 中,可以利用 reinterpret_cast 将 void* 重新解释为其他类型,但在 Go 中,这种操作是不安全的,因为 Go 语言没有定义结构体的内存模型,并且它可能会在不同的 Go 版本之间发生变化。 因此,在 Go 中处理二进制编码的推荐方法是使用 encoding/binary 包,该包可以将二进制数据直接解码为固定大小的结构体。这种方法既安全又高效,因为它不需要直接操作内存,并且可以确保数据在不同的平台上以一致的方式进行解码。

问题内容

在 c++ 中,您可以从 file 描述符读取数据,然后简单地将其重新解释到结构中以解释数据。

go 中有等效的方法吗?

作为一个非常人为的示例,请考虑以下内容,其中“processbytes”只是一个回调,其中为您提供了一个在从文件读取时连续附加的字节数组。

struct PayloadHeader {
  uint32_t TotalPayloadLength; 
  uint8_t  PayloadType;
};

struct TextMessage {
  PayloadHeader Header;
  uint32_t      SenderId;
  uint32_t      RecieverId;
  char          Text[64]; // null padded
};

void ProcessBytes(const uint8_t* data, size_t dataLength) {
  if(dataLength < sizeof(PayloadHeader))
    return;

  const PayloadHeader* header = reinterpret_cast(data);
  if(header.PayloadType == TEXT_MESSAGE) {
    if(header.TotalLength != sizeof(TextMessage))
      return;
    const TextMessage* text = reinterpret_cast(data);
    // Do something with the text message~

    // Adjust the *data* to 'erase' the bytes after we are done processing it
    // as a TextMessage
  }
}

解决方案


现在的答案建议使用 unsafe,但它们并没有讨论为什么你不应该使用 unsafe 以及你应该做什么。那我就来试试吧。

在您在 op 中发布的 c++ 代码中,您似乎正在编写一种二进制格式,它通过简单的转换读取数据。简单,但有效。我看到的唯一明显的问题是它不允许 little endian 和 big endian 之间的互操作性,但这是另一回事。

在 go 中处理二进制编码的方法是使用方便的包 encoding/binary,它能够将二进制数据直接解码为固定大小的结构(即没有字符串或切片,它们是可变长度的)因此长度需要任意编码)。

以下是我在 go 中实现您的示例的方法:

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

const textmessage = 11

func main() {
    // set up our data - this is an example of the data i
    // imagine you want to decode.
    r := bytes.newreader([]byte{
        // header
        byte(textmessagelen + headerlen), 0, 0, 0,
        11,

        // body
        137, 0, 0, 0,
        117, 0, 0, 0,
        // message content
        'h', 'e', 'l', 'l', 'o', '!', 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0, 0, 
    })

    // we first read the header to decide what to do next.
    // notice that we explicitly pass an argument that indicates to
    // parse integers using little endian, making this code portable.
    var h header
    err := binary.read(r, binary.littleendian, &h)
    if err != nil {
        fmt.println(err)
        return
    }


    switch h.type {
    case textmessage:
        // it's a text message - make sure the length is right.
        if textmessagelen != (int(h.length) - headerlen) {
            fmt.println("invalid payload length")
            return
        }

        // decode the data
        var t textmessage
        err = binary.read(r, binary.littleendian, &t)
        if err != nil {
            fmt.println(err)
            return
        }

        // print it out
        fmt.printf("sender: %d; receiver: %d\nmessage: %s\n",
            t.sender, t.receiver, bytes.trimright(t.text[:], "\x00"))
    default:
        fmt.println("unknown payload type")
    }
}

// if you need to find out what the encoded size of a struct is, don't use unsafe.sizeof;
// use binary.size instead.
var headerlen = binary.size(header{})

type header struct {
    length uint32
    type   uint8
}

var textmessagelen = binary.size(textmessage{})

type textmessage struct {
    sender, receiver uint32
    text             [64]byte
}

Playground

所以,这里有一些注意事项:

  • 在 go 中,二进制格式通常不会直接从内存中读取。这是因为 1. 它依赖于平台(小/大端),2. 字符串、切片和结构填充存在问题,3. 它是不安全的。如果你不直接篡改内存,go几乎可以保证你的程序无需任何修改就能在任何平台上流畅运行。一旦你开始这样做,你就失去了这种保证。
  • 我们不需要“提前”正在读取的数据的指针 - 我们将向下传递给 binary.readio.reader,这意味着当我们从中读取某些内容时,读取的数据将被丢弃,因此指针会自动前进。
  • 当你自己玩内存时,gc 可能会产生影响 - gc 可能认为数据中的某个点不再被引用并且可以自由使用 - 而实际上你仍在使用它,只是没有明确引用使用原生 go 指针。

你可以,但你不应该这样做,因为它不安全。 golang没有定义struct的内存模型(据我所知),它可能在golang版本之间发生变化。编组/解组是常规方法。

package main

import (
    "fmt"
    "unsafe"
)

type mys struct{
    a int
}

func main() {
    v := mys{0x1234abcd}
    unsafeArrayP := (*[unsafe.Sizeof(v)]byte)(unsafe.Pointer(&v))
    for i:=0;i<4;i++ {
        fmt.Printf("%x,", unsafeArrayP[i])
    }

    v2 := 0x1234abcd
    v3 := *((*mys)(unsafe.Pointer(&v2)))
    fmt.Println(v == v3)
}

打印 cd,ab,34,12,true

以上就是《在Golang中如何将 void* 转换为特定类型》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>