How do I manage memory across language boundaries?

Managing memory across language boundaries is a crucial aspect of system design, especially when integrating Go with other programming languages such as C or C++. When utilizing foreign function interfaces (FFI), understanding how to allocate, free, and manage memory is essential to avoid memory leaks and ensure efficient resource allocation.

In Go, memory is managed automatically via garbage collection, but interfacing with languages like C requires manual memory management. Here is an example showing how to allocate and free memory when using C code from Go:

package main /* #include #include char* allocateMemory(int size) { return (char*)malloc(size); } void freeMemory(char* ptr) { free(ptr); } */ import "C" import ( "fmt" "unsafe" ) func main() { // Allocate memory using C size := 100 cPtr := C.allocateMemory(C.int(size)) defer C.freeMemory(cPtr) // Use the memory goSlice := (*[100]C.char)(cPtr) for i := 0; i < size; i++ { goSlice[i] = C.char('A' + C.char(i % 26)) } fmt.Println("Allocated memory content:", C.GoStringN(cPtr, C.int(size))) }

Go memory management language interoperability Go C integration memory allocation foreign function interface