Calling Go func from C code via c-shared terminates process

Hello, I’m new to Go and coming from C, as such, I’m experimenting with -buildmode=c-shared, so far so good. Though, I ran into a problem where my C program exits after a function call because Go is internally calling os.Exit().

This terminate issue seems to happen when I try to cast a slice address to *C.char and return that as a C.struct member. This only happens on function return as the cast proceeds fine.

Here is my c-shared Go code:

package main

/*
typedef struct {
	char *ptr;
	int size;
} GoData;
*/

import (	
	"sync"
	"unsafe"
)


var slice = make([]byte, 1024)
var cdata = C.GoData{}

//export GetData
func GetData() C.GoData {
   cdata.size = 1024
   cdata.ptr = (*C.char)(unsafe.Pointer(&slice[0]))	   // Error: causes program to terminate on C side with Exit(2)
   //cdata.ptr = (*C.char)(C.malloc(C.sizeof_char * 1024)) // OK: seems to work fine
   return cdata
}

func main() {
}

Here is a list of questions I have:

  1. Is there anyway to prove or debug the os.Exit() is being called on Go side? So far I’m putting a break point on C side on ExitProcess()
  2. Why can’t I share unsafe.Pointer(&slice[0]) directly with C code? (Isn’t the c-shared memory in same process address space?)
  3. I’m resorting to this behavior because I’d like Go code to allocate the large memory chunks of data via sync.pool and share it with C code - avoiding memory copies and C code doing free. Any recommendation here?

Thanks a bunch!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.