先是类型对照

C语言类型CGO类型Go语言类型
charC.charbyte
singed charC.scharint8
unsigned charC.ucharuint8
shortC.shortint16
unsigned shortC.ushortuint16
intC.intint32
unsigned intC.uintuint32
longC.longint32
unsigned longC.ulonguint32
long long intC.longlongint64
unsigned long long intC.ulonglonguint64
floatC.floatfloat32
doubleC.doublefloat64
size_tC.size_tuint
bool懒得试int32

bool :0为false,1为true.

结构体的小例子

type DDOSINFO struct {
	time    int32     // 攻击时间 /分钟
	flag    int32     // 攻击类型
	target  [256]byte // 目标
	port    int32     // 端口
	nthread int32     // 线程
	count1  int32     //第一轮回参数
	count2  int32     //第二轮回参数
	bAttack int32
	dwToken uint32 //命令ID
}

typedef struct _MSGHEAD
{
    int time; // 攻击时间 /分钟
	int flag; // 攻击类型
	char target[256]; // 目标
	int  port; // 端口
	int nthread; // 线程
	int  count1;//第一轮回参数
	int  count2;//第二轮回参数
	BOOL bAttack;
	DWORD  dwToken;        //命令ID
}MSGHEAD,*PMSGHEAD;

Go中结构体转[]byte与[]byte转结构体

package main

import (
	"fmt"
	"unsafe"
)

type x struct {
	a string
	b []byte
	c int
}
type SliceMock struct {
	addr uintptr
	len  int
	cap  int
}

func main() {
	a := new(x)
	a.a = "121626"
	a.b = []byte("小学生到此一游")
	a.c = 8848
	Len := unsafe.Sizeof(*a) //sysinfo为结构体
	testBytes := &SliceMock{
		addr: uintptr(unsafe.Pointer(a)),
		cap:  int(Len),
		len:  int(Len),
	}
	data := *(*[]byte)(unsafe.Pointer(testBytes))    //data为[]byte
	ddosinfo := *(**x)(unsafe.Pointer(&data)) //data2为[]byte
	fmt.Println(ddosinfo)
}

来源

https://studygolang.com/articles/22044?fr=sidebar

https://www.jb51.net/article/144265.htm

说点什么
支持Markdown语法
在"Go与C通信"已有3条评论
Loading...