我正在努力制作我的第一个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()

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

import mymodule
mymodule.doStuff()

我收到以下错误:Trackback(最近的呼叫最后):文件“ mymoduletest.py”,第9行,在mymodule.dostuff(buffer)attributeError:'module'对象没有属性'dostuff'

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

有帮助吗?

解决方案

该代码有效的事实:

from mymodule.MyCustomType import MyCustomType

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

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

from mymodule import MyCustomType as therealmodule
therealmodule.doStuff()

或类似的 - 假设您给我们的信息,尤其是我从您说的代码中引用的第一行代码确实是准确的。

其他提示

你看到了什么 import mymodule 其次是 print(dir(mymodule)) ?

您的模块真的足够大,可以在3个文件上拆分吗?分裂确实增加了链接的复杂性...也许是名字缠绕?

AudioOutputOSX_doStuff 相对 MyModule_doStuff ...一个真正的问题,还是一个问题编辑的问题?

什么平台,什么编译器?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top