ctypes中的find_library()

时间:2014-05-22 10:37:10

标签: python ctypes

我正在尝试使用来自ctypes的命令find_library(),但我收到的错误是我不明白其原因。我正在使用Windows

这是代码:

import ctypes
from ctypes.util import find_library
import numpy
from string import atoi
from time import sleep

# Class constants
#nidaq = ctypes.windll.nicaiu
nidaq  = ctypes.cdll.LoadLibrary(find_library('NIDAQmx'))

这就是我得到的错误:

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    nidaq  = ctypes.cdll.LoadLibrary(find_library('NIDAQmx'))
  File "C:\Python27\lib\ctypes\__init__.py", line 443, in LoadLibrary
    return self._dlltype(name)
  File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__
    self._handle = _dlopen(self._name, mode)
TypeError: expected string or Unicode object, NoneType found

我应该将NIDAQmx放在特定的地方,以便找到它吗?或者这是无关的?

谢谢!

2 个答案:

答案 0 :(得分:8)

在Windows上,find_library搜索PATH环境变量中的目录,该变量不是Windows加载程序使用的真实search order for desktop applications。值得注意的是,find_library不包含应用程序目录和当前目录。

调用Windows SearchPath会更接近,但在给定activation contexts和其他API(例如SetDllDirectory或更新的API SetDefaultDllDirectoriesAddDllDirectory的情况下不会太近。

鉴于没有简单的方法来复制Windows加载程序使用的搜索,只需使用CDLL(cdecl)或WinDLL按名称加载DLL( STDCALL):

nidaq_cdecl   = ctypes.CDLL('NIDAQmx')
nidaq_stdcall = ctypes.WinDLL('NIDAQmx')

您可以在运行时动态地将DLL目录添加到PATH(与Linux加载程序在启动时对LD_LIBRARY_PATH的缓存相反)。例如,假设您的DLL依赖项位于&#34; dlls&#34;你的包的子目录。您可以按如下方式添加此目录:

import os

basepath = os.path.dirname(os.path.abspath(__file__))
dllspath = os.path.join(basepath, 'dlls')
os.environ['PATH'] = dllspath + os.pathsep + os.environ['PATH']

或者,您可以使用调用GetDllDirectorySetDllDirectory的上下文管理器来临时修改当前工作目录通常占用的搜索位置。请记住,就像修改PATH一样,这会修改全局流程数据,因此在使用多个线程时应该小心。这种方法的一个优点是它不会修改CreateProcess用于查找可执行文件的搜索路径。

import os
import ctypes
from ctypes import wintypes
from contextlib import contextmanager

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

def check_dword(result, func, args):
    if result == 0:
        last_error = ctypes.get_last_error()
        if last_error != 0:
            raise ctypes.WinError(last_error)
    return args

def check_bool(result, func, args):
    if not result:
        last_error = ctypes.get_last_error()
        if last_error != 0:
            raise ctypes.WinError(last_error)
        else:
            raise OSError
    return args

kernel32.GetDllDirectoryW.errcheck = check_dword
kernel32.GetDllDirectoryW.argtypes = (wintypes.DWORD,  # _In_  nBufferLength
                                      wintypes.LPWSTR) # _Out_ lpBuffer

kernel32.SetDllDirectoryW.errcheck = check_bool
kernel32.SetDllDirectoryW.argtypes = (wintypes.LPCWSTR,) # _In_opt_ lpPathName

@contextmanager
def use_dll_dir(dll_dir):
    size = newsize = 0
    while newsize >= size:
        size = newsize
        prev = (ctypes.c_wchar * size)()
        newsize = kernel32.GetDllDirectoryW(size, prev)
    kernel32.SetDllDirectoryW(os.path.abspath(dll_dir))
    try:
        yield
    finally:
        kernel32.SetDllDirectoryW(prev)

例如:

if __name__ == '__main__':
    basepath = os.path.dirname(os.path.abspath(__file__))
    dllspath = os.path.join(basepath, 'dlls')
    with use_dll_dir(dllspath):
        nidaq = ctypes.CDLL('NIDAQmx')

当然,如果您只对启动时设置DLL目录感兴趣,那么问题会更加简单。只需直接致电SetDllDirectoryW


另一种方法是使用标志LoadLibraryEx调用LOAD_WITH_ALTERED_SEARCH_PATH,这会将加载的DLL目录临时添加到搜索路径中。您需要使用绝对路径加载DLL,否则行为未定义。为方便起见,我们可以将ctypes.CDLLctypes.WinDLL子类化为LoadLibraryEx而不是LoadLibrary

import ctypes
from ctypes import wintypes

kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

def check_bool(result, func, args):
    if not result:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

kernel32.LoadLibraryExW.errcheck = check_bool
kernel32.LoadLibraryExW.restype = wintypes.HMODULE
kernel32.LoadLibraryExW.argtypes = (wintypes.LPCWSTR,
                                    wintypes.HANDLE,
                                    wintypes.DWORD)

class CDLLEx(ctypes.CDLL):
    def __init__(self, name, mode=0, handle=None, 
                 use_errno=True, use_last_error=False):
        if handle is None:
            handle = kernel32.LoadLibraryExW(name, None, mode)
        super(CDLLEx, self).__init__(name, mode, handle,
                                     use_errno, use_last_error)

class WinDLLEx(ctypes.WinDLL):
    def __init__(self, name, mode=0, handle=None, 
                 use_errno=False, use_last_error=True):
        if handle is None:
            handle = kernel32.LoadLibraryExW(name, None, mode)
        super(WinDLLEx, self).__init__(name, mode, handle,
                                       use_errno, use_last_error)

以下是所有可用的LoadLibraryEx标志:

DONT_RESOLVE_DLL_REFERENCES         = 0x00000001
LOAD_LIBRARY_AS_DATAFILE            = 0x00000002
LOAD_WITH_ALTERED_SEARCH_PATH       = 0x00000008
LOAD_IGNORE_CODE_AUTHZ_LEVEL        = 0x00000010  # NT 6.1
LOAD_LIBRARY_AS_IMAGE_RESOURCE      = 0x00000020  # NT 6.0
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE  = 0x00000040  # NT 6.0

# These cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH.
# Install update KB2533623 for NT 6.0 & 6.1.
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR    = 0x00000100
LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200
LOAD_LIBRARY_SEARCH_USER_DIRS       = 0x00000400
LOAD_LIBRARY_SEARCH_SYSTEM32        = 0x00000800
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS    = 0x00001000

例如:

if __name__ == '__main__':
    basepath = os.path.dirname(os.path.abspath(__file__))
    dllpath = os.path.join(basepath, 'dlls', 'NIDAQmx.dll')
    nidaq = CDLLEx(dllpath, LOAD_WITH_ALTERED_SEARCH_PATH)

答案 1 :(得分:1)

您要搜索的库是否位于计算机上的公共位置。 find_library不会对您的文件系统执行任意搜索,它会查找ctypes/macholib/dyld.py模块中列出的特定位置(请参阅dyld_find函数)。

如果你的图书馆在/usr/lib然后应该找到它,但如果它在非标准位置,则必须将其目录添加到环境变量DYLD_LIBRARY_PATH