如何在Go中创建一个可嵌入的C-API库?

huangapple go评论72阅读模式
英文:

How to create an embeddable C-API library in Go?

问题

我计划编写一个跨平台应用程序,大部分功能在所有平台(Linux、OS X、Windows、iOS、Android)上共享。这些功能主要是辅助函数(计算、内部列表、网络等),所以我觉得将这些函数放在一个库中,可以为每个平台编译,同时仍然能够为每个平台创建自定义的用户界面,会很方便。

我提到的这些平台上的主要语言是C、Objective-C、C#和Java。所有这些语言都支持直接调用库中的C-API函数,或通过内部包装器调用。由于我不想用C/C++编写我应用程序的80%代码,所以我搜索并找到了Go

cgo 似乎是解决我的问题的方法。
我目前的想法是用Go编写核心库,然后为每个平台编译它,但是调用go build并没有创建任何东西。
我使用import "C"导入了C代码。
我声明了一个func并在前面加上了//export语句。

我了解了gccgo,但人们一直指出它已经过时,不应该使用。

也许有人能指出我思考中的缺陷,或者帮助我将这个库文件整合在一起。提前谢谢。

英文:

I am planning to write a cross-platform app that has most of its functionality shared across all platforms (Linux, OS X, Windows, iOS, Android).
These are mostly helper function (calculations, internal lists, networking etc.) so I figured it would be convenient to have those functions in a library I can compile for every platform while still being able to create custom UI for each platform individually.

Dominant languages across those platforms I mentioned are C, Objective-C, C# and Java. All these languages support calling C-API functions from a library either directly or via internal wrappers. Since I don't want to write 80% of my application's code in C/C++, I searched and found Go.

cgo seems to be the solution for my problem.<br>
My current thought is to code the core library in Go and then compile it for each platform, however, invoking go build does not create anything at all.<br>
I import &quot;C&quot;.<br>
I have declared a func and added the //export statement before.

I read about gccgo but people keep pointing out that it is outdated and should not be used.

Maybe anyone can point out a flaw in my thoughts or help me bring this library file together. Thanks in advance.

答案1

得分: 0

如果你的目标是构建一个可以链接到任意C、Objective-C或Java程序的库,那么目前发布的标准工具链无法满足你的需求。虽然未来有计划改变这一点,但目前Go运行时不可嵌入到其他应用程序中。

虽然cgo可以让你导出函数供C调用,但这只在需要从Go调用的C代码需要回调到Go时才真正有用。

英文:

If your aim is to build a library that can be linked into arbitrary C, Objective-C or Java programs, you are out of luck with the currently released standard tool chain. There are plans to change this in the future, but at present the Go runtime is not embeddable in other applications.

While cgo will allow you to export functions to be called from C, this is only really useful for cases when the C code you call from Go needs to call back to Go.

huangapple
  • 本文由 发表于 2015年6月2日 01:59:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/30580111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定