title: golang support for shared memory
body: <p>I heard the slogan in golang about shared memory via communication, but here I have a need to write an application to interact with an existing application A using shared memory. Basically A writes a big chunk of data in memory (so big that it's inefficient to other other means of IPC), and wait for a program B to process it and report the result to A. </p>
  
  <p>Would like to write the program B using golang due to its scriptability and speed,   but don't see the direct support for shared memory. Thought of using C interface in golang but there is a problem with passing pointers between the two languages.</p>
  
  <p>Any ideas? Thanks!</p>
  
  <p><strong>UPDATE1</strong>: 
     Forgot to mention this is on Ubuntu 12.04. Thanks for asking.</p>
  
  <p><strong>UPDATE2</strong>:
     Created a simple program to test the reading of data pointed to by C pointer. </p>
  
  <p>golang code called "reader.go"</p>
  
  <pre><code>import "C"
  import "unsafe"
  import "fmt"
  
  func read(filename string) string {
      f := C.CString(filename)
      defer C.free(unsafe.Pointer(f))
      s := C.testc(f)
      defer C.free(unsafe.Pointer(s))
      return C.GoString(s)
  }
  
  func main() {
      fmt.Println(read("tmp"))
  }
  </code></pre>
  
  <p>C code called wrapper.c</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;errno.h&gt;
  
  char buf[0x10000];
  
  char* testc(char* filename){
      printf("reading file %s\n", filename);
      FILE *fp = fopen(filename, "r");
      fread(buf, 1, 100, fp);
      fclose(fp);
      return buf;
  }
  </code></pre>
  
  <p>When running <code>go run reader.go</code>, got a stackdump on go (too long to include here). </p>
  
  <p><strong>UPDATE 3</strong>:</p>
  
  <p>Find the line that caused go to crash: <code>defer C.free(unsafe.Pointer(s))</code>
  Without it, things works fine. </p>
  
  <p>Credit: the code snippet is adapted from <a href="https://gist.github.com/jedy/3282764" rel="nofollow">https://gist.github.com/jedy/3282764</a>. </p>