开发者

Path-independant management of shared C libs inside a Python package

Say I have a package called Foo organized this way:

Foo\
    __init__.py
    foo.py
    bar.py
    lib\
        libwhatever.so

My module foo.py uses python ctypes to wrap the C-methods contained in my libwhatever.lib, which involves checking the lib is where it should be. 2 questions:

1) How to check in my package that the required lib is at its place (in Foo\lib), wherever the entire Foo package has been placed ?

Right now, the path to my lib is hard-coded but, as I may distribute things later, the problem will come.

2) Then I have module bar.py which packs a slower Python version of the C-routines inside libwhatever. I would like to use them instead whether the import of libwhatever fails. Is there a way to abstractly switch between the C and Python version of the routines wrt the success or failure of the lib开发者_运维问答rary importation ?

Thank you in advance for your advice.


Assuming you're on Linux, I think you'll have to either add that .so file to your library search path, or add the module directory to your path. Have a look at ldconfig. man ldconfig. Once you do either of those, you could use ctypes.util.find_library(). Otherwise you would have to have the full path to the .so file to use cdll().

What I think I would do is just build that path at run time- so something kind of like this:

from ctypes import CDLL
import Foo
try:
    MyLib = CDLL(Foo.__path__[0] + '/lib/libwhatever.so')
except OSError:
    from Foo import bar as MyLib

Though, there may be a better way...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜