title: How to return a string from JSON to a C caller (Golang CGO)?
body: <p>I'm trying to develop a routine in Go that will be called by a C++ program.  The Go looks like the following:</p>
  
  <pre><code>package main
  
  import (
      "C"
      "encoding/json"
      "log"
  )
  
  type keydata struct {
      Key   string `json:"key"`
      Error string `json:"Error"`
  }
  
  func lookupKey() string {
  //simplified to remove the call to web service
      body := "{\"key\": \"blahblah\", \"Error\": \"\"}"
  
      k := keydata{}
      err := json.Unmarshal([]byte(body), &amp;k)
      if err != nil {
          log.Fatal(err)
      }
  
      return k.Key
  }
  
  //export GetKey
  func GetKey() string {
      theKey := lookupKey()
      return theKey
  }
  
  func main() {}
  </code></pre>
  
  <p>If I substitute some hard coded value for the return k.Key statement everything works fine and the C or C++ can call the exported GetKey function.  When I try to return the decoded JSON string from k.Key or even just return the string from the variable named body - I receive an error:</p>
  
  <p>runtime error: cgo result has Go pointer
  goroutine 17 [running, locked to thread]</p>
  
  <p>I'm building this as follows:</p>
  
  <p>go build -buildmode=c-archive example.go</p>
  
  <p>The C++ is built as follow: </p>
  
  <p>g++ -pthread test.cpp example.a -o test</p>
  
  <p>What am I missing to make this work without raising a panic error? I'm digging around to find an answer but have yet to resolve this.</p>
  
  <p>@JimB &amp; @Jsor, thank you so much for your responses.  Returning a *C.char certainly worked.  I'm left wondering though, when I return it as a Go string behind the scenes in the auto generated header file Go actually creates and passes a C struct named GoString that contains a char array named p and the length named n.  As long as I pass a hard-coded string instead of k.Key it actually works and I can interrogate the auto-generated char array in C++.  When I try to return k.Key, a string it throws that exception.  Is it possible to cast the Go string or add some notation to the export decoration to make it work?  </p>
  
  <p>I can certainly return the C.CString char array and make it work - thank you! I'm just also wanting to understand why it works when returning a hard coded string and not in the example I've posted.</p>
  
  <p>Thank you both for your time and explanations.</p>