Python与SWIG - 单个.pyd(.so)中的多个模块
我正在用SWIG为Python写一个C++扩展。根据我对Python和SWIG的理解,每个模块都必须有自己的.pyd文件。比如说,如果我有一个叫'mymodule'的模块,就应该有一个对应的'_mymodule.pyd'文件。
在我的情况下,我希望只用一个'pyd'文件,而多个模块都能链接到这个文件。
mypackage/
mypackage/__init__.py
mypackage/module1.py
mypackage/module2.py
我不想维护多个.pyd文件,所以我可以把我的接口(.i)文件都放在VS2010的同一个项目里。
编辑:到目前为止,我能让它工作的唯一方法是把我的'pyd'文件复制成两个新文件:_module1.pyd和_module2.pyd。但我不喜欢这个方法,因为我需要不必要地复制一个30MB的'pyd'文件。我更希望这些模块能链接到一个'_package.pyd'文件。
有什么好的方法可以做到这一点吗?
2 个回答
-1
我也遇到了同样的问题,我的解决办法是使用Python的ctypes模块。
spclient_python.pyd是一个特殊的文件,叫做pydll,它有两个初始化函数,一个是官方的,叫做initspclient_python,和dll的名字一样;另一个模块叫做example,有一个初始化函数叫做initexample。每个Python模块在dll中都有一个对应的initXXXXXXX函数。
import ctypes
testlib = ctypes.PyDLL("spclient_python.pyd") #this will call initspclient_python
testlib.initexample() # here I am manually calling initexample function inside spclient_python.pyd
import sys
print (sys.modules.keys()) # this will display all the modules imported...spclient_python and example will show
import spclient_python # this is for me to use the module in the code below
import example
test1=spclient_python.test1()
test2=example.test2()
0
最后,最简单也是“正确”的做法就是创建多个小项目,只调用大项目中一些公开的部分。然后,SWIG会处理这些小项目,生成Python模块。这样做效果非常好。