Created
October 21, 2021 21:29
-
-
Save leaanthony/7689a00ee51af3ce64745e8d4644ba6f to your computer and use it in GitHub Desktop.
Simple C String allocations manager for Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
calloc
A simple, dependency free wrapper for managing your C string allocations in Go.
Usage
c := NewCalloc()
defer c.Free()
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 ;-)