Changing LD_LIBRARY_PATH at runtime for ctypes

后端 未结 5 1950
南笙
南笙 2020-11-27 15:14

How do you update this environment variable at runtime so that ctypes can load a library wherever? I\'ve tried the following and neither seem to work.

from c         


        
5条回答
  •  情深已故
    2020-11-27 15:44

    Even if you give a fully qualified path to CDLL or cdll.LoadLibrary(), you may still need to set LD_LIBRARY_PATH before invoking Python. If the shared library you load explicitly refers to another shared library and no "rpath" is set in the .so for that library, then it won't be found, even if it has already been loaded. An rpath in a library specifies a search path to be used to search for other libraries needed by that library

    For example, I have a case of a set of interdependent third-party libraries not produced by me. b.so references a.so. Even if I load a.so in advance:

    ctypes.cdll.LoadLibrary('/abs/path/to/a.so')
    ctypes.cdll.LoadLibrary('/abs/path/to/b.so')
    

    I get an error on the second load, because b.so refers to simply 'a.so', without an rpath, and so b.so doesn't know that's the correct a.so. So I have to set LD_LIBRARY_PATH in advance to include '/abs/path/to'.

    To avoid having to set LD_LIBRARY_PATH, you modify the rpath entry in the .so files. On Linux, there are two utilities I found that do this: chrpath, and patchelf. chrpath is available from the Ubuntu repositories. It cannot change rpath on .so's that never had one. patchelf is more flexible.

提交回复
热议问题