我正在编写一个小程序来使用 Go 检查字节序:
var i int = 0x0100
ptr := unsafe.Pointer(&i)
if 0x01 == *(*byte)(ptr) {
fmt.Println("Big Endian")
} else if 0x00 == *(*byte)(ptr) {
fmt.Println("Little Endian")
} else {
// ...
}
Run Code Online (Sandbox Code Playgroud)
我import "unsafe"打包转换*int为*byte. 但正如https://golang.org/pkg/unsafe/ 中提到的:
包 unsafe 包含绕过 Go 程序类型安全的操作。
导入不安全的包可能是不可移植的,不受 Go 1 兼容性指南的保护。
有没有更好的方法来确定字节序,还是我必须使用不安全的包?
我正在测试从另一个目录导入.proto文件。
$ GOPATH / src / A / A.proto
syntax = "proto3";
package A;
message SomeMsg {
string msg = 2;
int64 id = 3;
}
Run Code Online (Sandbox Code Playgroud)
$ GOPATH / src / B / B.proto
syntax = "proto3";
package B; import "A/A.proto";
message Msg {
SomeMsg s = 1;
}
Run Code Online (Sandbox Code Playgroud)
我正在这样做:在文件夹A中:
protoc A.proto --go_out=.
Run Code Online (Sandbox Code Playgroud)
然后在文件夹B中:
protoc B.proto --go_out=. --proto_path=$GOPATH/
Run Code Online (Sandbox Code Playgroud)
但是我会得到这个错误:
B.proto:文件不位于使用--proto_path(或-I)指定的任何路径内。您必须指定包含此文件的--proto_path。请注意,proto_path必须是.proto文件名的精确前缀-protoc太笨拙,无法找出两个路径(例如绝对路径和相对路径)是否相等(这比您想象的要难得多)。
我使用 protobuf 定义了 3 种消息类型。(MsgA, MsgB, MsgC)
Message MsgA {
string content;
int64 A;
};
Message MsgB {
string content;
char B;
};
Message MsgC {
string content;
double C;
};
Run Code Online (Sandbox Code Playgroud)
我定义了一个 MsgType 来指示消息是 MsgA/MsgB/MsgC
Message MsgType {
string type; // indicate MsgA/ MsgB/ MsgC
};
Run Code Online (Sandbox Code Playgroud)
然后,我生成了一些消息并以这种格式存储在内存映射文件中:
|MsgType|MsgA/MsgB/MsgC|some end marker|
Run Code Online (Sandbox Code Playgroud)
当我从缓冲区读取时,我想做类似的事情:
msgType := &MsgType{}
err := proto.Unmarshal(byteArrayforMsgType, msgType)
...
switch msgType.GetType() {
case "MsgA":
a := &MsgA{}
err := prto.Unmarshal(byteArrayforMsg, a)
...
case "MsgB":
b := &MsgB{}
err := prto.Unmarshal(byteArrayforMsg, …Run Code Online (Sandbox Code Playgroud) 我正在 golang 中实现一个网络数据包。它已经在 C++ 中实现了。目的是让golang实现的客户端与C++实现的服务器进行通信。
他们将通过数据包进行通信。数据包结构是:
type Packet struct {
length uint32
nameLen uint8
data []byte
} // in golang
struct Packet {
uint32_t length;
uint8_t nameLen;
byte data[];
} // in C++
Run Code Online (Sandbox Code Playgroud)
它们的下划线结构是字节数组。接收字节数组格式的消息时。我们需要把它翻译成Packet。
auto p = reinterpret_cast<Packet*>(buffer); // in c++
(buffer's alignment is manually set as 64)
p := (Packet)(unsafe.Pointer(&buffer)) // in golang
Run Code Online (Sandbox Code Playgroud)
为了让它们通信,它们的结构对齐应该保持不变。
问题来了:打印出他们的对齐方式后,我得到了这个:
type Packet struct {
length uint32 // alignment 8
nameLen uint8 // alignment 8
data []byte // alignment 8
}
struct Packet {
uint32_t …Run Code Online (Sandbox Code Playgroud) 网上查了一下,runtime包有这个功能,但是没有导出。
Golang 在 C++ 中有类似 memmove 的东西吗?
void * memmove ( void * destination, const void * source, size_t num );