ZGo (part 2): Calling Go from Zig===============================Following our last post Calling Zig from Go, we can also utilize Zig to call Go. There are two possible approaches here, using go tool to generate C and importing it in Zig, or building a library and linking it with Zig. I opted for the library route from Go. It should be a more general use-case that can be applied to other languages as well. Environment Assumptions:*************************
Files:****** |
8@8888@88888% X88X8@XXXX@XX%8888888 88 @888@88X8888@8X@8@X%@%. t@88@88888 8X888@8S .: 88X::S ;8@88@S@ 8: 8@8 :8@@ . .@88%8t8 .8X%:@S8 888@8 S.;@ .88@8 ;; . ;88888 @888X;:: . t 8888S. . @S8@@X8: 88X8@8%@@8X@88t;t;88Xt8@8X8SX888 X@@88@88888@;X;@ X8S@8@8SX8@888@ 8@88888X8888 :%S SS;@@X@@8888888 @@X88888@8X8@;. @%;8X@88888888S8 8X88S8S88S@8@8 @ X8X@SX88888888SX 8888888X8888X888@SX8@@888888@8888 SX@8S8S88@S8S8888XSX888@8@@88X8S@ @X@8S88888S888X888@8X 8:888X88888 8@S88tt8XX ;;X8@@@8X:8 X8S888X8X8 ; SXX@@8@: @8:XXX 88888.tX8 @8X888SS8X@ S8 XX88;8 8t8SSX8. 8@%88X88888888888X8 @X888@. 8@X8@88@8 X88XS 8@8888@@ 8%888S8 @8@8%X 8XX@X@@S 8 888S888 8S@88t.8SSS%:.8%% ;SS@8 .88888888 8X88S888:.@ .@ 8:t8;Xt.8X%8S8S8tt 8X8SXS;XX 8:. S@;:. @S8S888@ 8X8888X: %8X@S%X@8SS%X%St8@888S8: 888888X@@@X;8%8X8@St8t8;8@X888888 X88888@8SXSSt8@88XS%8@@XSS8S8888 8X88S@88%8SX8S88SX88X%8@8S8%8S8 8@X888@8S888S88888X@@888888888 88X88888888X888S88@888888S8; 8X88888X888S8888@88@88 . X 88; 88@8888888X8S88888 .@;8 X8X8 8@X%888X ;88 |
Here we need the comment decoration to export our HelloGopher symbol for Zig to use.
Using the @cImport and @cInclude built-ins we can import the header file autogenerated by the Go c-archive build process. This translates the header from C to Zig, to see what is generated by this process you can run zig translate-c libhello.h after the build process.
There is not much that has changed from our last build.zig, other than the steps being reversed. We need to call the go step before our default step so we can link the produced library with our Zig program. Note that for the library to be found it must be named libhello.a and be produced in our defined Library search path (the current directory.) Running zig build go && zig build will compile the executable.Calling Go!
Conclusion:*************Zig and Go interop feels painless. Both are innovative languages with different but compatible goals. Go has the advantage of a huge ecosystem of libraries and being able to tap into that with Zig seamlessly is a powerful tool. There has been a handful of times when I wanted to vendor a library that simply did not exist in C, and having Go as an additional option will help cover more bases. |