使用 ctypes 加载 DLL 失败

问题描述 投票:0回答:1

我使用专有的 Python 包。在此 Python 包中,以下 DLL 加载命令失败。

scripting_api = ctypes.CDLL("scripting_api_interface")

找不到模块“scripting_api_interface”(或其依赖项之一)。尝试使用带有构造函数语法的完整路径。

我知道 DLL scripting_api-interface.dll 的路径,并在我的 Python 代码中添加了以下 DLL 路径。

os.environ['PATH'] = 'L:\win64' + os.pathsep

但是仍然加载DLL会失败。我创建了一个测试环境,使用以下命令。

scripting_api = ctypes.CDLL("L:\win64\scripting_api_interface.dll")

效果符合预期。但我无法更改 DLL 调用,因为它是由提到的 Python 包提供的。还有其他选项可以让它运行吗?

python dll ctypes dllimport
1个回答
0
投票

在导入包之前使用可用的版本调用

CDLL
。 一旦 DLL 被加载,额外的加载将被忽略。

示例 (Win11 x64)...

test.c(简单的 DLL 源,MSVC:cl /LD test.c):

__declspec(dllexport)
void func() {}

当 test.dll 位于当前目录中时,如果没有不在“标准”搜索路径中的 DLL 的显式路径,则加载将失败。 出于安全原因,当前目录不是搜索路径的一部分。

>>> import ctypes as ct
>>> dll = ct.CDLL('test')
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    dll = ct.CDLL('test')
  File "C:\dev\Python313\Lib\ctypes\__init__.py", line 390, in __init__
    self._handle = _dlopen(self._name, mode)
                   ~~~~~~~^^^^^^^^^^^^^^^^^^
FileNotFoundError: Could not find module 'test' (or one of its dependencies). Try using the full path with constructor syntax.
>>> dll = ct.CDLL('./test')  # explicit relative path works
>>> dll = ct.CDLL('test')    # now without path works because already loaded
>>>

因此,在您的情况下,以下内容应该有效:

import ctypes as ct
ct.CDLL('L:/win64/scripting_api_interface.dll')
import your_package
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.