在Python中提供Go接口的实现是否可能?

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

Is it possible to provide implementation of Go interface from Python?

问题

我有一个Go库,可以对变量数据进行并发处理,我有一个(简化的)接口:

type Handler interface {
    Accepts(id []byte) bool
    ProcessUnit(u []byte) []byte
}

目前,库的最终开发者(用户)可以编写实现该接口的Go代码,并且库可以处理最终开发者的数据结构。

现在的问题是:(跳过开销),是否可以提供用另一种语言编写的该接口的实现(以Python为例)?我的意图是提供一个“插件API”,以便任何人都可以添加使用Python(或其他语言)编写的处理程序。

我已经有一个使用zeromq在Go和Python之间传递数据的工作实现,但这感觉“不自然”。我想要实现的理想状态是,库用户将plugins.py文件放在预定义的位置,然后Go可以在启动时自动加载插件,这可行吗?还是我方向错了?

英文:

I have a Go lib which does concurrent processing on variable data, I have a (simplified) interface:

type Handler interface {
    Accepts(id []byte) bool
    ProcessUnit(u []byte) []byte
}

Currently, library end-developer (user) might write go code which implements this interface and a library can work on end-developer data structures.

Now the real question: (lets skip overhead), is it possible to provide implementation of that interface written in another language (with Python in mind)? My intention is to provide a "Plugin API" so anyone can add handlers, written in eg: Python (or possibly other languages)

I already have a working implementation which uses zeromq to pass data around go<->python, but this feels "non-natural". The utopia I want to achieve is that an lib user places plugins.py file in predefined location, and go can load plugins automatically on startup, is it possible or I'm looking in wrong direction?

答案1

得分: 1

Go语言在零阶和一阶近似中没有动态加载模块的功能,所以不能简单地将plugins.py放在某个地方,然后让Go程序加载和使用它,至少不能直接从Go语言本身来做到这一点...

...但是你可以尝试使用go-python(https://github.com/sbinet/go-python)或goPy(https://github.com/qur/gopy),它们应该允许你从Go语言中运行Python解释器,而Python解释器可以进行动态模块加载。这样做可能会在Go语言和Python之间来回传递数据,有些麻烦,但应该是可行的。

通过zeromq或者直接使用net/rpc包来传递数据在我看来并不是“不自然”的...

(附注:如果有人能够编写合适的Python代码,并得到一些关于指针的帮助,他应该能够在几天内编写出Go代码。)

英文:

Go has no dynamic loading of modules (at least in zero and first order approximation), so no, you cannot just place a plugins.py somewhere and have a Go programm load and use it, at least not from Go itself...

...But you might be able to use go-python https://github.com/sbinet/go-python or goPy https://github.com/qur/gopy which should allow you to run the python interpreter from Go and the python interpreter can do dynamic module loads. This will get a bit ugly with some forth and back between Go and Python but should be doable.

Passing data around (either zeromq or maybe direct via package net/rpc) doesn't seem "non-natural" to me...

(Sidenote: If somebody can write proper Python code and gets some help understanding pointers he should be able to write Go code in a few days.)

huangapple
  • 本文由 发表于 2013年12月19日 21:27:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/20683015.html
匿名

发表评论

匿名网友

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

确定