CGO unpinned Go pointer panic

242 views
Skip to first unread message

Brent Bailey

unread,
Jan 7, 2024, 9:06:35 PM1/7/24
to golang-nuts
I'm trying to pass a pointer to an external C library using Go 1.21 and get the following runtime panic:
panic: runtime error: cgo argument has Go pointer to unpinned Go pointer

My first attempt was:
var bufferSize int = 0
C.external_library(...,(*C.size_t)(unsafe.Pointer(&bufferSize)))

I tried to pin the memory using the Pinner type in the runtime library:
var bufferSize int = 0
ptr := &bufferSize
var p runtime.Pinner
p.Pin(ptr)

C.external_library(...,(*C.size_t)(unsafe.Pointer(ptr)))

p.Unpin()
which resulted in the same error.

I tried creating the pointer in C as follows:
var ptr unsafe.Pointer
ptr = C.malloc(C.size_t(4))

C.external_library(...,(*C.size_t)(ptr))

bufferSize := *(*int)(ptr)
C.free(ptr)
but the error persisted.

What am I doing wrong? 

Tamás Gulácsi

unread,
Jan 8, 2024, 3:21:34 AM1/8/24
to golang-nuts
That should work. Are you sure that those ellipses (...) does not contain some other pointers?
Reply all
Reply to author
Forward
0 new messages