2

I am trying to use Cgo to export a function that initializes a zap logger. The function is written in Go but I am working towards the goal of being able to call this function in a C script and actually use the function in the C script. For example, my init function looks like this:

func initLogger() *zap.Logger {
    logger, _ := zap.NewProduction()
    return logger
}

Now, I want to be able to use this function in a c script by exporting it using cgo. So, I would do //export initLogger and then build a .so and .h file from this go file and link it to a c script to build an executable. So basically, in my C script, I want to be able to do something like :

logger = initLogger()
logger.Info("Hello World!")

This would log: {"level":"info","ts":1654031030.1591902,"caller":"go-kitLog/exLogger.go:14","msg":"Hello World!"}

The problem I am facing is that *zap.Logger does not export to C, it gives this error: Go type not supported in export: *zap.Logger. Have any of you possibly dealt with a similar situation? If so, how did you solve it?

  • See: https://stackoverflow.com/questions/6125683/call-go-functions-from-c And, see: https://stackoverflow.com/a/32217287/5382650 The latter lists four criteria (e.g. can't use "fancy" stuff) so the go function has to be in the main package. So, you'll have to define a wrapper function around your current object/member function – Craig Estey May 31 '22 at 22:26
  • I actually had to do something similar just recently. The project had flatbuffers library available, so I opted for packaging the structured messages on the C++ side info an FB blob, passing the pointer to buffer to Go, then feeding that stuff to the logger. Suppose, can not be done any easier than that. – oakad Jun 01 '22 at 03:20
  • @oakad Thank you for your reply, I believe your solution will work for my project, however, I am a bit unclear on the details just relying on your comment. Is there any way we can chat about it on Reddit or Discord? – softdev2022 Jun 02 '22 at 17:35
  • I don't mind chatting, but don't use neither reddit nor discord. You can drop me an email to "my username" at yahoo.com. – oakad Jun 03 '22 at 08:00

0 Answers0