Skip to content

Instantly share code, notes, and snippets.

@leaanthony
Created October 21, 2021 21:29
Show Gist options
  • Save leaanthony/7689a00ee51af3ce64745e8d4644ba6f to your computer and use it in GitHub Desktop.
Save leaanthony/7689a00ee51af3ce64745e8d4644ba6f to your computer and use it in GitHub Desktop.
Simple C String allocations manager for Go.
package yourpackage
/*
#include <stdlib.h>
*/
import "C"
import "unsafe"
// Calloc handles alloc/dealloc of C data
type Calloc struct {
pool []unsafe.Pointer
}
// NewCalloc creates a new allocator
func NewCalloc() Calloc {
return Calloc{}
}
// String creates a new C string and retains a reference to it
func (c Calloc) String(in string) *C.char {
result := C.CString(in)
c.pool = append(c.pool, unsafe.Pointer(result))
return result
}
// Free frees all allocated C memory
func (c Calloc) Free() {
for _, str := range c.pool {
C.free(str)
}
c.pool = []unsafe.Pointer{}
}
@leaanthony
Copy link
Author

calloc

A simple, dependency free wrapper for managing your C string allocations in Go.

Usage

  1. Create a new allocator: c := NewCalloc()
  2. Defer the free method: defer c.Free()
  3. Start creating C strings: myCString := c.String("I am a C string")

Why?

It's a common pattern when using CGO to allocate C strings, use them in a CGO call then deallocate them once the call is complete. This method not only cleans up your code (only 1 defer) but ensures that all allocated memory gets freed.

NOTE: This isn't thread safe as it is not intended to be shared between threads. It is better to create new allocators where needed.

Why isn't this a package?!?

Try it and you'll C why ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment