go 私有結構體 私有方法 映射


  1. 通過go:linkname的方式把方法init11映射出來
  2. 通過struct的bytes轉換的方式把私有的結構體轉換成當前包的結構體

a.go

github.com/pubgo/gotests/testmonkey_patch/internal/a1/a.go

type hh struct {
	HH string
}

func (t hh) init1() string {
	return t.HH
}

func Newhh(s string) *hh {
	return &hh{HH: s}
}

main.go

github.com/pubgo/gotests/testmonkey_patch/main.go

import (
	"context"
	"fmt"
	"github.com/pubgo/gotests/testmonkey_patch/internal/a1"
	_ "google.golang.org/grpc"
	"net"
	"reflect"
	"unsafe"
	_ "unsafe"
)

type hh struct {
	HH string
}

//go:linkname init11 github.com/pubgo/gotests/testmonkey_patch/internal/a1.(*hh).init1
func init11(t *hh) string

func main() {
	hh := a1.Newhh("sss")
	fmt.Println(hh.HH)
	dt := MyStructToBytes(unsafe.Pointer(hh))
	fmt.Println(BytesToMyStruct(dt).HH)
	hh1 := BytesToMyStruct(dt)
	fmt.Println(init11(hh1))
}

var sizeOfMyStruct = int(unsafe.Sizeof(hh{}))

func MyStructToBytes(s unsafe.Pointer) []byte {
	var x reflect.SliceHeader
	x.Len = sizeOfMyStruct
	x.Cap = sizeOfMyStruct
	x.Data = uintptr(s)
	return *(*[]byte)(unsafe.Pointer(&x))
}

func BytesToMyStruct(b []byte) *hh {
	return (*hh)(unsafe.Pointer(
		(*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
	))
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM