0

我正在制作我的第一个 Python C 扩展,它定义了一些函数和自定义类型。奇怪的是自定义类型正在工作,但不是常规功能。顶级 MyModule.c 文件如下所示:

static PyMethodDef MyModule_methods[] = {
    {"doStuff", MyModule_doStuff, METH_VARARGS, ""},
    {NULL, NULL, 0, NULL} /* Sentinel */
};

static struct PyModuleDef MyModule_module = {
    PyModuleDef_HEAD_INIT,
    "mymodule",
    "Documentation",
    -1,
    MyModule_methods
};

PyMODINIT_FUNC PyInit_audioDevice(void) {
    PyObject *object = PyModule_Create(&MyModule_module);
    if(object == NULL) {
        return NULL;
    }

    if(PyType_Ready(&MyCustomType_type) < 0) {
        return NULL;
    }

    Py_INCREF(&MyCustomType_type);
    PyModule_AddObject(object, "MyCustomType", (PyObject*)&MyCustomType_type);

    return object;
}

我正在使用这个 setup.py 文件构建扩展:

from distutils.core import setup, Extension
setup(name = "mymodule",
      version = "1.0",
      ext_modules = [Extension("mymodule", ["MyModule.c", "MyCustomType.c", "DoStuff.c"])])

“DoStuff”文件将其功能定义为:

static PyObject*
AudioOutputOSX_doStuff(PyObject *self, PyObject *args) {
  printf("Hello from doStuff\n");
  return Py_None;
}

有趣的是 MyCustomType 类型工作正常,因为我可以实例化它:

from mymodule.MyCustomType import MyCustomType
foo = MyCustomType()

我从自定义类型的 new 和 init 方法中看到我的 printf() 语句打印出来了。但是,此代码失败:

import mymodule
mymodule.doStuff()

我收到以下错误: Traceback(最近一次调用最后一次):文件“MyModuleTest.py”,第 9 行,在 mymodule.doStuff(缓冲区)中 AttributeError:“模块”对象没有属性“doStuff”

这里发生了什么?我的模块的方法声明中是否有一些错误?

4

2 回答 2

2

这段代码有效的事实:

from mymodule.MyCustomType import MyCustomType

绝对令人惊讶,它告诉我们它mymodule实际上是一个,以及MyCustomType该包中的一个模块(其中包含同名的类型或类)。

因此,要调用该函数,您显然必须这样做:

from mymodule import MyCustomType as therealmodule
therealmodule.doStuff()

or the like -- assuming the info you give us, particularly that first line of code which I've quoted from code you say works, is indeed exact.

于 2010-09-23T02:18:21.143 回答
0

如果你import mymodule跟着,你会看到什么print(dir(mymodule))

你的模块真的大到可以分成 3 个文件吗?拆分确实为链接增加了很多复杂性……也许是名称修改?

AudioOutputOSX_doStuffMyModule_doStuff......一个真正的问题,还是只是一个问题编辑问题?

什么平台,什么编译器?

于 2010-09-22T23:30:08.173 回答