github.com/imgk/memory-go@v0.0.0-20220328012817-37cdd311f1a3/memory_cgo.go (about)

     1  //go:build malloc_cgo
     2  
     3  package memory
     4  
     5  // #include <stdlib.h>
     6  import "C"
     7  
     8  import "unsafe"
     9  
    10  // pointer is ...
    11  type pointer struct {
    12  	Pointer uintptr
    13  }
    14  
    15  // Alloc is ...
    16  func Alloc[T any](n int) (pointer, []T) {
    17  	ptr := uintptr(C.malloc(C.size_t(n * int(unsafe.Sizeof(*(new(T)))))))
    18  	return pointer{Pointer: ptr}, unsafe.Slice((*T)(unsafe.Pointer(ptr)), n)
    19  }
    20  
    21  // Free is ...
    22  func Free(p pointer) {
    23  	C.free(unsafe.Pointer(p.Pointer))
    24  }