【问题标题】:"Exported" functions in cython pyd modulecython pyd 模块中的“导出”函数
【发布时间】:2014-08-19 10:33:50
【问题描述】:

我正在使用 cython 将我的 python 脚本编译为 .pyd 模块。 我的 python 脚本如下所示:

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

如何使所有类和函数只能在已编译模块内访问? 所以基本上我希望 pyd 模块仅“导出” main() 函数而已。

编辑: 一个来自 cython-users 的人给了我解决方案:pre-declare class as

cdef object MyClass

所以我的代码应该是这样的

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

【问题讨论】:

  • 请发布给定的解决方案作为答案...您可以获得一些支持并关闭此问题

标签: python cython


【解决方案1】:

老实说,对于您的应用程序,您可能无法做到。这样做的方法是将你的函数和类转换为 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 函数不支持闭包,我相信这意味着它们也不支持生成器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多