c/c++语言开发共享集成C和Python:ValueError:模块函数不能设置METH_CLASS或METH_STATIC

我正在第一次尝试集成C和Python 2.7.3。 首先,我只是想为Python编写一个可以进行基本添加的C模块。 (它被称为npfind,因为一旦我弄明白了,我想为numpy编写一个find方法)

npfind.h:

#include  extern int add(int a, int b); 

npfind.c:

 #include "npfind.h" int add(int a, int b) { return a + b; } 

pynpfind.c:

 #include "Python.h" #include "npfind.h" static char* py_add_doc = "Adds two numbers."; static PyObject* py_add(PyObject* self, PyObject* args) { int a, b, r; if (!PyArg_ParseTuple(args, "ii", &a, &b)) { return NULL; } r = a + b; return Py_BuildValue("i", r); } static PyMethodDef* _npfindmethods = { {"add", py_add, METH_VARARGS, py_add_doc}, {NULL, NULL, 0, NULL} }; void init_npfind(void) { PyObject* mod; mod = Py_InitModule("_npfind", _npfindmethods); } 

npfind.py:

 from _npfind import * #Do stuff with the methods 

npfindsetup.py

 from distutils.core import setup, Extension setup(name="npfind", version="1.0", py_modules = ['npfind.py'], ext_modules=[Extension("_npfind", ["pynpfind.c", "npfind.c"])]) 

毕竟,在Windows 7上,我输入

 python npfindsetup.py build_ext --inplace --compiler=mingw32 

这似乎工作。 当我尝试找到npfind.py时,我收到此错误:

 Traceback (most recent call last): File "npfind.py", line 1, in  from _npfind import * ValueError: module functions cannot set METH_CLASS or METH_STATIC 

我无法弄清楚它在说什么。 什么是METH_CLASS和METH_STATIC,为什么我要设置它们?

    您将_npfindmethods声明为指针,并尝试将其初始化为数组。 当我构建从您的代码段复制的代码时,我收到很多警告,例如:

     ac:24:5: warning: braces around scalar initializer [enabled by default] ac:24:5: warning: (near initialization for '_npfindmethods') [enabled by default] ac:24:5: warning: initialization from incompatible pointer type [enabled by default] ac:24:5: warning: (near initialization for '_npfindmethods') [enabled by default] (...) 

    变量用不正确的值初始化,因此Python在里面找到随机数据。


    您应该将_npfindmethods声明为数组:

     static PyMethodDef _npfindmethods[] = { {"add", py_add, METH_VARARGS, py_add_doc}, {NULL, NULL, 0, NULL} }; 

    现在它将按照您的预期进行初始化。 另外,因为现在py_add_doc需要具有常量地址,所以你必须使它成为一个数组:

     static char py_add_doc[] = "Adds two numbers."; 

    所以,你的最终pynpfind.c看起来像:

     #include "Python.h" #include "npfind.h" static char py_add_doc[] = "Adds two numbers."; static PyObject* py_add(PyObject* self, PyObject* args) { int a, b, r; if (!PyArg_ParseTuple(args, "ii", &a, &b)) { return NULL; } r = a + b; return Py_BuildValue("i", r); } static PyMethodDef _npfindmethods[] = { {"add", py_add, METH_VARARGS, py_add_doc}, {NULL, NULL, 0, NULL} }; void init_npfind(void) { PyObject* mod; mod = Py_InitModule("_npfind", _npfindmethods); } 

      以上就是c/c++开发分享集成C和Python:ValueError:模块函数不能设置METH_CLASS或METH_STATIC相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/550035.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐