Python ctypes: loading DLL from from a relative path

前端 未结 4 1649
挽巷
挽巷 2020-12-15 04:40

I have a Python module, wrapper.py, that wraps a C DLL. The DLL lies in the same folder as the module. Therefore, I use the following code to load it:



        
相关标签:
4条回答
  • 2020-12-15 05:18

    You can use os.path.dirname(__file__) to get the directory where the Python source file is located.

    0 讨论(0)
  • 2020-12-15 05:20

    Expanding on Matthew's answer:

    import os.path
    dll_name = "MyCDLL.dll"
    dllabspath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + dll_name
    myDll = ctypes.CDLL(dllabspath)
    

    This will only work from a script, not the console nor from py2exe.

    0 讨论(0)
  • 2020-12-15 05:30

    I always add the directory where my DLL is to the path. That works:

    os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH']
    windll.LoadLibrary('mydll.dll')
    

    Note that if you use py2exe, this doesn't work (because __file__ isn't set). In that case, you need to rely on the sys.executable attribute (full instructions at http://www.py2exe.org/index.cgi/WhereAmI)

    0 讨论(0)
  • 2020-12-15 05:41

    Another version:

    dll_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyCDLL.dll')
    myDll = ctypes.CDLL(dll_file)
    
    0 讨论(0)
提交回复
热议问题