英文:
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 "C"
.<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论