cython pyd模块中的“导出”功能

时间:2014-06-28 12:09:46

标签: python cython

我使用cython将我的python脚本编译为.pyd模块。 我的python脚本看起来像:

    class WorkingThread(QtCore.QThread):
    ...
    class Ui_Dialog(object):
    ...
    def Function1():
    ...
    def Function2():
    ...
    def main():
    ...

如何才能在编译模块中访问所有类和函数? 所以基本上我想要pyd模块来" export"只有main()函数了。

编辑: 来自cython用户的人给了我解决方案:预先声明类为

cdef object MyClass

所以我的代码看起来像

cdef object WorkingThread
cdef object Ui_Dialog
class WorkingThread(QtCore.QThread):
...
class Ui_Dialog(object):
...
cdef Function1():
...
cdef Function2():
...
def main():
...

1 个答案:

答案 0 :(得分:0)

老实说,对于你的应用程序,你可能不会。这样做的方法是将函数和类转换为cdef函数和类,然后从main函数调用它们。但是,如果您希望能够从普通的python类(例如QThread)派生,那么您将无法对所有内容进行模糊处理。这是一个示例,展示了什么是暴露的,什么不会暴露:

def Function1():
    # This function will be exposed
    pass

cdef Function2():
    # But this cdef function will not
    pass

cdef class UI_Dialog: 
    # This class will be exposed

    cdef object storage # This member won't be exposed

    def def_func(self): 
        # This member function will be available
        pass

    cdef cdef_func(self):
        # But this one will not be available
        pass

#cdef class WorkingThread(QTCore.QThread):
    # This wouldn't even compile; cdef classes can't
    # derive from non cdef classes

class WorkingThread(QTCore.QThread):
    # This is a normal python class, and is exposed

    def __init__(self):
        #You're free to call cdef functions in here
        Function2()
        self.dialog = UI_Dialog()

        #But you can't access cdef members,
        #So the following wouldn't compile
        #self.dialog.storage
        #self.dialog.cdef_func()

        # But you can access def members
        self.dialog.def_func()

cdef hidden_main():
    # This function isn't exposed, and you can also call
    # cdef functions in here, and access cdef members
    Function1()
    Function2()
    dialog = UI_Dialog()
    dialog.def_func()
    dialog.cdef_func()
    dialog.storage = dict()
    workingThread = WorkingThread()

def main():
    # Here you can just call your hidden_main
    hidden_main()

基本上你要隐藏的任何逻辑都需要在cdef函数中,你根本不能隐藏类,但是你可以隐藏这些类的成员的可访问性。如果你想隐藏一个类的成员,它需要是一个cdef类,而那些不能从Python类派生。

同样重要的是要注意,你不能简单地将任何普通的python函数转换为cdef函数(尽管我认为这是最终的目标)。目前cdef函数不支持闭包,我相信这意味着它们也不支持生成器。