【问题标题】:how use ctypes with msvc*.dll from within matlab on windows如何在 Windows 上的 matlab 中将 ctypes 与 msvc*.dll 一起使用
【发布时间】:2015-06-11 04:04:59
【问题描述】:

我在 windows 7/64、matlab 2015a 上使用 winpython (2.7) 和 matlab 的新 python bridge

>> py.ctypes.util.find_library('c')

ans = 

  Python str with no properties.

    msvcr90.dll

>> py.ctypes.util.find_msvcrt()

ans = 

  Python str with no properties.

    msvcr90.dll

>> py.ctypes.CDLL(py.ctypes.util.find_library('c'))
Python Error: [Error 1114] A dynamic link library (DLL) initialization routine failed

>> x=CDLL('C:\Users\nlab\Downloads\WinPython-64bit-2.7.9.5\python-2.7.9.amd64\msvcr90.dll')
Python Error: [Error 1114] A dynamic link library (DLL) initialization routine failed

还会出现一个弹出窗口:

Microsoft Visual C++ Runtime Library
R6034 "an application has made an attempt to load the c runtime library incorrectly"

a couple other SO answers 建议它的 matlab 将其不兼容的 msvc*.dll 副本放在路径上的某个位置,所以我删除了 sys.path 中不是来自 WinPython 的所有内容(只是 matlab 的 \bin\win64\\Python27\site-packages\ 来自我有另一个 python 安装):

>> py.pprint.PrettyPrinter().pprint(py.sys.path)
['',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\python27.zip',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\DLLs',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\plat-win',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\lib-tk',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\FontTools',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\win32',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\win32\\lib',
 'C:\\Users\\nlab\\Downloads\\WinPython-64bit-2.7.9.5\\python-2.7.9.amd64\\lib\\site-packages\\Pythonwin']

仍然有大量的 msvc*.dll 散布在系统上,而且肯定有一些在 PATH 上:

>> x = py.os.environ

x = 

  Python _Environ with properties:

    data: [1x1 py.dict]

    {'TMP': 'C:\\Users\\nlab\\AppData\\Local\\Temp', <<snip>>, 'USERPROFILE': 'C:\\Users\\nlab'}

>> cellfun(@(s)fprintf('%s\n',s),strsplit(char(x{'PATH'}),';'))
C:\Program Files\Haskell\bin
C:\Program Files\Haskell Platform\2014.2.0.0\lib\extralibs\bin
C:\Program Files\Haskell Platform\2014.2.0.0\bin
C:\Users\nlab\Downloads\WinPython-64bit-2.7.9.5\python-2.7.9.amd64
C:\Users\nlab\Downloads\opencv\build\x64\vc12\bin
C:\ProgramData\Oracle\Java\javapath
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0\bin\
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0\libnvvp\
C:\Program Files\ImageMagick-6.8.3-Q16
C:\Program Files (x86)\OSSBuild\GStreamer\v0.10.7\bin
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.1\\bin
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.1\libnvvp\
C:\Program Files (x86)\PHP\
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Program Files\Intel\DMIX
C:\Program Files\TortoiseSVN\bin
C:\Program Files\SlikSvn\bin\
C:\Program Files\MySQL\MySQL Server 5.5\bin
C:\Program Files (x86)\Common Files\Acronis\SnapAPI\
C:\Program Files (x86)\PostgreSQL\9.2\bin
C:\Python27
C:\Python27\Scripts
C:\Program Files\Microsoft SQL Server\110\Tools\Binn\
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Program Files (x86)\LilyPond\usr\bin
C:\Program Files (x86)\Git\cmd
C:\Program Files\Microsoft Windows Performance Toolkit\
C:\Program Files\TortoiseGit\bin
C:\Program Files (x86)\QuickTime\QTSystem\
C:\Program Files (x86)\Skype\Phone\
C:\Program Files\Mosek\7\tools\platform\win64x86\bin
C:\Program Files\Haskell Platform\2014.2.0.0\mingw\bin
C:\Users\nlab\AppData\Roaming\cabal\bin
C:\Program Files (x86)\SSH Communications Security\SSH Secure Shell
C:\Gtk+\bin

我注意到在C:\Program Files\MATLAB\R2015a\bin\win64\ 中我们只有msvc[r|p][100|110].dll——这是否意味着它不适用于基于 msvcr90 的 python 发行版,如 winpython 2.7.9.5?

【问题讨论】:

  • msvcr90.dll 的初始化调用FindActCtxSectionString 在当前激活上下文中寻找“msvcr90.dll”。如果此调用失败,则卸载,返回FALSE,加载程序报告初始化失败。通常对于 Python 2.7,此激活上下文由嵌入在 python.exe 中的清单提供。但是,您也可以在运行时修改激活上下文。请参阅我对How do I load a C DLL from the SXS in Python? 的回答。
  • 感谢@eryksun,这看起来很有希望。但是我不熟悉这些东西,你能给我一些背景吗?就像我试图将 python 指向 matlab 的 msvcr 或 v/v 一样,为什么他们不能各自对自己感到满意?他们中的一个人正在使用它不期望的 msvcr 会很危险吗?我的清单应该是什么样的?您的 .py 代码不需要更改,对吗?我真的很想从 matlab 中正常工作,他们的安装很复杂,所以我不能真正编辑他们的 cdll 调用 -- github.com/Toblerity/Shapely/blob/master/shapely/libgeos.py
  • 显然我必须使用matlab的——用CDLL('C:\\Program Files\\MATLAB\\R2015a\\bin\\win64\\msvcr100.dll')替换shapely的CDLL(find_library('c'))使它一切正常——所以@eryksun,如果我理解,你的方法将是一种确定正确路径的方法自动使用?
  • 嗯,一位身材匀称的开发人员建议只使用ctypes.cdll.msvcrt——可行——我认为这应该等同于find_library('c')?无论如何,那么你不需要任何花哨的清单/激活上下文的东西......
  • 这取决于它使用 CRT 做什么。例如,使用不同的 CRT 打开需要与解释器和其他扩展模块共享的文件(即FILE * 和底层文件描述符)是错误的。但如果它在没有崩溃的情况下工作,那么它可能没问题。

标签: python matlab ctypes msvcrt msvcr90.dll


【解决方案1】:

将此定义为文件msvc.py:

import ctypes
print ctypes.cdll.msvcrt

然后在matlab中:

>> py.importlib.import_module('msvc')
<CDLL 'msvcrt', handle fe190000 at 771c2b38>

ans = 

  Python module with properties:

    ctypes: [1x1 py.module]

    <module 'msvc' from 'msvc.pyc'>

>> x = py.ctypes.cdll

x = 

  Python LibraryLoader with properties:

    msvcrt: [1x1 py.ctypes.CDLL]

    <ctypes.LibraryLoader object at 0x00000000771D6278>

>> x.msvcrt

ans = 

  Python CDLL with no properties.

    <CDLL 'msvcrt', handle fe190000 at 771c2b38>

我不知道为什么必须使用 msvc.py —— 仅导入 ctypes 不会为您提供带有 msvcrt 属性的 cdll

【讨论】:

  • 您的 MATLAB 界面无法处理 cdll 的动态 __getattr__ 设计。你不能简单地使用msvcrt = py.ctypes.CDLL('msvcrt')来加载DLL吗? cdll 使用内置的 setattr 将结果缓存在自身上。
【解决方案2】:

@eryksun 的方法有效。

问题仍然存在,为什么 ctypes.cdll.msvcrtfind_library('c') 以它们的方式实现?他们应该只使用@eryksun 的方法来返回python 清单中的dll,对吗?

from ctypes import *
from ctypes.wintypes import *

kernel32 = WinDLL("kernel32")

ACTCTX_FLAG_PROCESSOR_ARCHITECTURE_VALID = 0x001
ACTCTX_FLAG_LANGID_VALID = 0x002
ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004
ACTCTX_FLAG_RESOURCE_NAME_VALID = 0x008
ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x010
ACTCTX_FLAG_APPLICATION_NAME_VALID = 0x020
ACTCTX_FLAG_HMODULE_VALID = 0x080
DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION = 1

INVALID_HANDLE_VALUE = HANDLE(-1).value
ULONG_PTR = WPARAM  # pointer-sized unsigned integer

class ACTCTX(Structure):
    _fields_ = (("cbSize", ULONG),
                ("dwFlags", DWORD),
                ("lpSource", LPCWSTR),
                ("wProcessorArchitecture", USHORT),
                ("wLangId", LANGID),
                ("lpAssemblyDirectory", LPCWSTR),
                ("lpResourceName", LPCWSTR),
                ("lpApplicationName", LPCWSTR),
                ("hModule", HMODULE))

    def __init__(self, *args, **kwds):
        super(ACTCTX, self).__init__(sizeof(self), *args, **kwds)

CreateActCtxW = kernel32.CreateActCtxW
CreateActCtxW.restype = HANDLE
CreateActCtxW.argtypes = (POINTER(ACTCTX),)
ReleaseActCtx = kernel32.ReleaseActCtx
ReleaseActCtx.restype = None
ReleaseActCtx.argtypes = (HANDLE,)
ActivateActCtx = kernel32.ActivateActCtx
ActivateActCtx.argtypes = (HANDLE, POINTER(ULONG_PTR))
DeactivateActCtx = kernel32.DeactivateActCtx
DeactivateActCtx.argtypes = (DWORD, ULONG_PTR)

def getMsvcr90():
    ctx = ACTCTX(hModule = cdll.python27._handle 
                ,lpResourceName = c_wchar_p(2)
                ,dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID
                )
    hActCtx = CreateActCtxW(byref(ctx))
    if hActCtx == INVALID_HANDLE_VALUE:
        raise WinError()

    cookie = ULONG_PTR()
    if not ActivateActCtx(hActCtx, byref(cookie)):
        raise WinError()
    msvcr90 = CDLL("msvcr90")
    if not DeactivateActCtx(0, cookie):
        raise WinError()

    ReleaseActCtx(hActCtx)

    # show DLL path
    hModule = HANDLE(msvcr90._handle)
    path = (c_wchar * 260)()    
    kernel32.GetModuleFileNameW(hModule, path, len(path))
    print(path.value)

    return msvcr90

【讨论】:

  • 我突然想到,即使 LoadLibraryW(u'msvcr90')GetModuleHandleW(u'msvcr90') 在没有完全限定路径或激活上下文的情况下将无法工作,但如果您确定您的进程只有一个实例/版本在加载 msvcr90.dll 后,您可以改为调用 EnumProcessModules 来获取模块句柄数组,然后调用 GetModuleBaseNameW 来查找基本名称等于 u'msvcr90.dll' 的模块。然后您可以将其包装在 CDLL 实例中,例如msvcr90 = CDLL('msvcr90', handle=hModule).
  • 由于_ctypes扩展模块直接暴露了几个CRT函数的地址,更可靠的获取CRT句柄的方法是调用GetModuleHandleExW。例如:import ctypes;hMsvcr = ctypes.c_void_p();GMHEXF_FROM_ADDRESS = 4;ctypes.windll.kernel32.GetModuleHandleExW(GMHEXF_FROM_ADDRESS, ctypes.memset, ctypes.byref(hMsvcr));msvcr = ctypes.CDLL('msvcr', handle=hMsvcr.value)
  • 如果您在使用动态__getattr__ 时遇到问题,请尝试将函数引用为ctypes.windll['kernel32']['GetModuleHandleExW']
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2011-06-08
  • 2020-02-03
相关资源
最近更新 更多