This might seem like a silly question, but is it possible to write a library in GO that can be called from other languages, e.g. C++?
That's unfortunately not directly ("can be called") possible. There are some issues wrt what is defined by the platform's C implementation (for most/all of the officially supported platforms):
All of the above applies to 'gc'. The same is to certain extent relaxed in 'gccgo'. More info about this in C C_Interoperability.
Your best bet is JSON-RPC. I've been looking around for ways to integrate legacy Python code with Go, to no success, until I found this. If your data structures can be converted to JSON, you are good to go. Here's a silly example:
Go JSON-RPC server
import (
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
type Experiment int
func (e *Experiment) Test(i *string, reply *string) error {
s := "Hello, " + *i
*reply = s
log.Println(s, reply)
return nil
}
func main() {
exp := new(Experiment)
server := rpc.NewServer()
server.Register(exp)
l, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal("listen error:", err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
server.ServeCodec(jsonrpc.NewServerCodec(conn))
}
}
Python client
import json
import socket
s = socket.create_connection(("127.0.0.1", 1234))
s.sendall(json.dumps(({"id": 1, "method": "Experiment.Test", "params": ["World"]})))
print s.recv(4096)
Response
{"id":1,"result":"Hello, World","error":null}