【问题标题】:How to import cython generated files in golang using cgo如何使用 cgo 在 golang 中导入 cython 生成的文件
【发布时间】:2019-02-05 06:03:23
【问题描述】:

我将我的 python 文件 cythonized 为 example.c 和 example.so 我可以将这些文件导出为 python 模块并访问 python 中的函数 测试.py:

import example
example.test()

这样我可以很容易地在 python 中导入我的 cythonized python 文件。 我如何使用 cgo 在 golang 中类似地导入这些文件?

【问题讨论】:

  • 您可以从 C 访问 cython 功能,从而将其导入 cgo。这是你的想法吗?请更具体地说明您要实现的目标。
  • 我想在 golang 中调用 example.test 方法,类似于我在 python 中调用 example.test 方法
  • 您知道吗,要使 Cython 代码正常工作,必须运行 Python 解释器。你将不得不以某种方式管理它。它不会像“导入示例”那么简单。

标签: python go cython cgo


【解决方案1】:

Cython 代码包含一堆包装代码以创建 Python 模块并在 Python 对象和 C 类型之间进行转换。

您可能不需要任何这些。例如,cgo 中一个非常简单的 hello world 可能只是:

/* hello.c */
#include <stdio.h>

static void hello(void) {
    printf("hello world!\n");
}

您可以使用特殊导入和一些包含指令 cmets 从 GO 使用 C 代码调用它:

package main

// #include <hello.c>
import "C"

func main() {
    C.hello()
}

您当然可以尝试仅包含上述“cythonized”C 文件,但您还需要包含适当的链接器指令,以便 Go 可以将所有 Python 运行时内容编译到您的 Go 二进制文件中。

一般来说,这可能不是您想要做的......

如果您真的想从 Go 调用 Python,您可能需要查看 http://grump.io/ 之类的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2013-09-22
    相关资源
    最近更新 更多