Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go c-shared library callback into other languages

I am in the process of developing a library that will be written in Go and compiled down to a C shared library so it can be called by languages such as Python, Node.JS, Java and Ruby

I have just realised that there will be an issue when it comes to callbacks. How can I callback into the calling code which will be at least one of the above languages? Is there a single way I can do it or will I need to implement something specific on the Go side for each language?

Update for clarity:

I am already able to build Go as a library and execute the code from other languages such as Java and Python.

My question specifically relates to a situation where go is running something asynchronously and needs to call back into the caller (i.e. Java, Python).

like image 575
jim Avatar asked Apr 04 '16 04:04

jim


2 Answers

The lingua franca of interfacing between different programming languages is to go through C. You can use something like cgo to make your Go code accessible through C, then use the C or "native" bindings in Python, Java, etc to invoke it.

Usually developers only go through this much trouble for large and well-maintained projects. If you have a personal project and if performance is less of a concern, I would suggest communicating via json (for web languages) or stdout/stderr pipes (probably more what you want). You can print commands to stdout from Ruby and have your Go code process the request and report back on its stdout. It's usually possible although sometimes tricky to pipe both input and output to another program. CGI programs work this way, spawning off interpreters for other languages and piping data to that interpreter.

Update: Calling back into the Java/Python/whatever language runtime from Go is difficult if you want to pass objects; I imagine that will need to be crafted differently depending on the binding API (Java, Python). Maybe you have already tackled this problem if you have the bindings in place? It might be easier if you can get away with not passing any parameters to the callback (i.e. it's basically a timer callback). Minimize the data which needs to be generated in Go and read in the other language.

like image 73
dwks Avatar answered Oct 04 '22 14:10

dwks


Well, this is gonna be a mostly link-only answer, however since Go 1.5 you can produce shared libraries that you can call from C, or any language that supports that (aka python, ruby, php, etc)

http://blog.ralch.com/tutorial/golang-sharing-libraries/

  • this is not my link, I've briefly followed it before to make a dummy python test.
like image 45
OneOfOne Avatar answered Oct 04 '22 14:10

OneOfOne