[cgo] go strings and go pointers

77 views
Skip to first unread message

Miłosz Pigłas

unread,
Jul 26, 2016, 7:23:56 AM7/26/16
to golang-nuts
Hello everyone,

I'm experimenting with extension for sqlite written in Go. This is simple function exported to shared library, which produces string from recived arguments. If such function returns value (which is result of concatenation of strings that were created in C code) as GO string, program starts panicking with message 'cgo result has Go pointer'. When I return C string instead Go string everything works as expected. Also I noticed, that when program calls other exported function, which returns value that is known on compile time, it doesn't crash.

I'm curious what is difference between first case, when function returns concatenation of arguments passed from C code and program starts panicking and second one when function returns 'constant' expression? Does it mean, that constant string expression, known on compile time doesn't contain Go pointer and doesn't apply to CGO rules https://golang.org/cmd/cgo/#hdr-Passing_pointers?

Kind reagards,
Milosz

Tamás Gulácsi

unread,
Jul 26, 2016, 10:11:02 AM7/26/16
to golang-nuts
You have to allocate ön the C side if you pass it to C, esp. pointers.

Uli Kunitz

unread,
Jul 26, 2016, 10:43:44 AM7/26/16
to golang-nuts
It is ensured that the C string is deallocated (freed) by SQLite? Otherwise you have a memory leak.

Returning a GO string cannot work for two reasons:

  1. Go strings are under management of the GC and might reallocate the string memory while the C code is running.
  2. Go strings have not the same format as C strings. See here: http://research.swtch.com/godata
 
Reply all
Reply to author
Forward
0 new messages