C++ app with Golang modules

Hi everyone,

I have a C++ app and I am thinking of rewriting parts of it in Go. The way this would work would be:

  • The C++ app loads the .dylib (on macOS) and .dll (on Windows) and calls the Go functionality when needed.
  • Functions in the Go .dylib/dll would call function pointers in the main C++ process for existing functionality written in C++.

What are your thoughts on this? Has anyone tried anything similar?

Appreciate any feedback you might have.

You can do this with cgo. Though you should know that cgo is not Go.

You can build Go as a shared lib using the c-shared buildmode. This will let you call Go from C++.

From Go references to C:

Calling C function pointers is currently not supported, however you can declare Go variables which hold C function pointers and pass them back and forth between Go and C. C code may call function pointers received from Go.

Thank you @nathankerr.

Yes, using cgo is something that I tried to avoid due to the overhead on the calls - though I’ve read it should be better with Go 1.8.

Still not sure which way would be better in terms of performance and development speed.

a) Go app that loads C++ .dll/.dylib
or
b) C++ app that loads Go .dll/.dylib

There will always be overhead for cgo calls. This is because of the fundamental difference between how call stacks are handled.

Hard to say which would be better. I would start by seeing if I could get the go tool to build the entire app. In effect, having go.main do nothing other than calling c++.main. This is a bit more than option a, but would allow the most flexibility for choosing which part of the app to convert (e.g., top down, bottom up, or some combination of the two).

Any progress on this? I’ve been trying to chew through a similar situation; Not sure if the best approach is wrapping a C++ lib with C so I could call that from go, use swig, or re-write in go. I’d love to share references.

Other references for now:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.