github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/freeze/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"syscall"
     6  	"unsafe"
     7  )
     8  
     9  /*
    10  #include <sys/types.h>
    11  #include <sys/mman.h>
    12  #include <unistd.h>
    13  */
    14  import "C"
    15  
    16  const PageSize = 4096
    17  
    18  type Example struct {
    19  	A, B, C int64
    20  }
    21  
    22  func (example *Example) Freeze() *Example {
    23  	// note this must be later explicitly freed
    24  	page := C.malloc(PageSize)
    25  
    26  	result := (*Example)(unsafe.Pointer(page))
    27  	*result = *example
    28  
    29  	C.mprotect(page, PageSize, syscall.PROT_READ)
    30  
    31  	return result
    32  }
    33  
    34  func main() {
    35  	a := &Example{1, 2, 3}
    36  	a = a.Freeze()
    37  
    38  	a.B = 123
    39  	fmt.Println(a)
    40  }