Documentation
¶
Overview ¶
This package provides a buffer that can be converted to a Go string or used in C functions that require a pointer to a C string. The advantage of this library is that the string is stored as a null-terminated C string in a Go slice, and memory management is handled by Go.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ByteConstraint ¶
ByteConstraint is a type constraint that restricts the type to an 8-bit number. Since C.char can be signed or unsigned, this library permits either.
type CString ¶
type CString[T ByteConstraint] []T
CString is a buffer that can be converted to a Go string or used in C functions that require a pointer to a C string. Go will handle the memory allocation and freeing.
Example ¶
cStr := New[byte]("hello\n\tworld 😊!")
ptr := unsafe.Pointer(cStr.Pointer())
if cStringEquals(ptr, "hello\n\tworld 😊!") {
fmt.Println("strings are equal")
}
Output: strings are equal
func Make ¶
func Make[T ByteConstraint](n int) CString[T]
Make creates a new CString with the given length in bytes. The provided length includes the null terminator. For example, the string "hello\0" has length 6. Panics if the length is less than 1.
func New ¶
func New[T ByteConstraint](s string) CString[T]
New creates a new null-terminated CString from the given Go string. Panics if the specified Go string contains a null character.
func NewWithCheck ¶
func NewWithCheck[T ByteConstraint](s string) (CString[T], error)
NewWithCheck creates a new null-terminated CString from the given Go string. Returns an error if the specified Go string contains a null character.
func (CString[T]) Bytes ¶
Bytes returns a slice containing the Go string representation of the CString, but under the hood the underlying slice data is not copied.
func (CString[T]) Pointer ¶
func (s CString[T]) Pointer() *T
Pointer returns the pointer to the first element of the CString. This function does not perform any conversions because the string is already stored internally as a null-terminated C string, so it is very fast. To avoid being flogged by an angry mob, please follow the rules for passing Go pointers to C: https://pkg.go.dev/cmd/cgo#hdr-Passing_pointers