为什么go build找不到Py_None?

2024-03-28 08:42:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为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库显然正在加载。这是怎么回事?你知道吗


Tags: pybuildcomnoneconfiggoexamplestatus
1条回答
网友
1楼 · 发布于 2024-03-28 08:42:54

多亏了Ismail Badawi的注释,答案是用C编写一个不返回任何值的函数。这是必需的,因为Py_None是一个宏,Go看不到。你知道吗

无.c

#define Py_LIMITED_API
#include <Python.h>

PyObject *IncrNone() {
        Py_RETURN_NONE;
}

我的模块.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()
}

相关问题 更多 >