为什么go build找不到Py_None?

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

Why isn't go build finding Py_None?

问题

我正在为Python封装一个Go库。我需要能够返回None,但在编译时找不到它:

/*
#cgo pkg-config: python3
#define Py_LIMITED_API
#include <Python.h>
*/
import "C"

//export Nothing
func Nothing(self, args *C.PyObject) (status *C.PyObject) {
    C.Py_IncRef(C.Py_None)
    return C.Py_None
}

这是go build的输出:

go build -buildmode=c-shared -o mymodule.so
# example.com/mywrapper
/tmp/go-build293667616/example.com/mywrapper/_obj/_cgo_main.o:(.data.rel+0x0): undefined reference to `Py_None'
collect2: error: ld returned 1 exit status

我不明白为什么它可以找到所有其他的Py*函数和类型(PyArgs_ParseTuplePyLong_FromLong都可以正常工作),但找不到Py_None。显然已经加载了Python库。这是怎么回事?

英文:

I'm wrapping a Go library for Python. I need to be able to return None, but it's not finding it at compile time:

/*
#cgo pkg-config: python3
#define Py_LIMITED_API
#include &lt;Python.h&gt;
*/
import &quot;C&quot;

//export Nothing
func Nothing(self, args *C.PyObject) (status *C.PyObject) {
    C.Py_IncRef(C.Py_None)
    return C.Py_None
}

Here's the output of go build

go build -buildmode=c-shared -o mymodule.so
# example.com/mywrapper
/tmp/go-build293667616/example.com/mywrapper/_obj/_cgo_main.o:(.data.rel+0x0): undefined reference to `Py_None&#39;
collect2: error: ld returned 1 exit status

I'm not understanding how it can be finding all of the other Py* functions and types (PyArgs_ParseTuple and PyLong_FromLong work just fine), but can't find Py_None. The Python library is obviously being loaded. What's going on here?

答案1

得分: 1

感谢Ismail Badawi的评论,答案是编写一个在C中返回None的函数。这是必需的,因为Py_None是一个宏,Go无法看到它。

none.c

#define Py_LIMITED_API
#include <Python.h>

PyObject *IncrNone() {
        Py_RETURN_NONE;
}

mymodule.go

/*
#cgo pkg-config: python3
#define Py_LIMITED_API
#include <Python.h>

PyObject *IncrNone();
*/
import "C"

//export Nothing
func Nothing(self, args *C.PyObject) (status *C.PyObject) {
        return C.IncrNone()
}
英文:

Thanks to a comment from Ismail Badawi, the answer is to write a function in C that returns None. This is required because Py_None is a macro, which Go can't see.

none.c

#define Py_LIMITED_API
#include &lt;Python.h&gt;

PyObject *IncrNone() {
        Py_RETURN_NONE;
}

mymodule.go

/*
#cgo pkg-config: python3
#define Py_LIMITED_API
#include &lt;Python.h&gt;

PyObject *IncrNone();
*/
import &quot;C&quot;

//export Nothing
func Nothing(self, args *C.PyObject) (status *C.PyObject) {
        return C.IncrNone()
}

huangapple
  • 本文由 发表于 2016年11月19日 10:20:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/40688567.html
匿名

发表评论

匿名网友

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

确定