cutil: add general C type, function and const aliases

This change adds a new pointer alias CPtr, that should always only
contains pointers to C allocated memory and should always used for
such pointers in order to keep them separate from Go pointers more
easily. This is helpful, since only CPtr are allowed to be stored in
C allocated memory, and Go pointers can only be passed to C functions
if they don't point to memory not containing Go pointers again, that
is all pointers in such memory must be CPtr.

The change also adds aliases for C.malloc and C.free that return and
accept the CPtr type as a little safety measure.

Additionally there are some useful constants defined.

Signed-off-by: Sven Anderson <sven@redhat.com>
This commit is contained in:
Sven Anderson 2021-01-11 19:04:53 +01:00 committed by mergify[bot]
parent c995d63088
commit 0130c60281

View File

@ -1,12 +1,20 @@
package cutil
/*
#include <stdlib.h>
typedef void* voidptr;
*/
import "C"
import (
"unsafe"
)
// Basic types from C that we can make "public" without too much fuss.
// PtrSize is the size of a pointer
const PtrSize = C.sizeof_voidptr
// SizeTSize is the size of C.size_t
const SizeTSize = C.sizeof_size_t
// SizeT wraps size_t from C.
type SizeT C.size_t
@ -15,6 +23,9 @@ type SizeT C.size_t
// unsafe.Pointer but have specific types to help "self document" what the
// underlying pointer is really meant to represent.
// CPtr is an unsafe.Pointer to C allocated memory
type CPtr unsafe.Pointer
// CharPtrPtr is an unsafe pointer wrapping C's `char**`.
type CharPtrPtr unsafe.Pointer
@ -26,3 +37,9 @@ type SizeTPtr unsafe.Pointer
// FreeFunc is a wrapper around calls to, or act like, C's free function.
type FreeFunc func(unsafe.Pointer)
// Malloc is C.malloc
func Malloc(s SizeT) CPtr { return CPtr(C.malloc(C.size_t(s))) }
// Free is C.free
func Free(p CPtr) { C.free(unsafe.Pointer(p)) }