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