本文介绍了Python ctypes dll加载错误487的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.7并尝试使用ctypes加载dll:

I am using Python 2.7 and trying to load a dll with ctypes:

有时,它会抛出以下错误,而有时它会运行正常.同样对于Python 3总是会抛出此错误:

It sometimes throws the following error, some other times it runs ok. Also with Python 3 always throws this error:

推荐答案

我们在FIPS认证的OpenSSL版本中遇到了类似的问题.不幸的是,该版本的OpenSSL必须加载到特定的内存地址.如果在启动应用程序时尝试太晚加载OpenSSL,则它所需要的内存地址已被另一个依赖项占用.我们能找出的最好的解决方法"是确保将OpenSSL(libeay32.dll)尽快加载到内存地址空间中.

We were having a similar issue with a FIPS-certified version of OpenSSL. Unfortunately, that version of OpenSSL is required to be loaded at a specific memory address. If you try to load OpenSSL too late when starting an application, the memory address it requires has already been taken by another dependency. The best we could figure out to "fix" this is to ensure OpenSSL (libeay32.dll) is loaded into the memory address space as soon as possible.

在您的情况下,在Python脚本的 TOP 行中添加以下行(注意: ATTOP 意味着在任何其他可执行代码行之前,包括import语句)):

In your case, add the following lines AT THE TOP of your Python script (NOTE: AT THE TOP means before any other line of executable code, including import statements):

import ctypes
from ctypes import cdll
from ctypes.util import find_library
cdll.LoadLibrary(find_library('libeay32'))

或者,您可以确保 libeay32.dll mylib.dll 中列出的第一个依赖项.

Alternatively, you could ensure that libeay32.dll is the first dependency listed within mylib.dll.

开始编辑

在我的案例中,尽管上述代码有助于增加成功的可能性,但在某些情况下,它仍然太晚加载了OpenSSL DLL.要解决此问题,我必须使用以下代码在C ++中创建一个新的Python包装器可执行文件:

While the above code helped increase the probability of success in my case, it still loaded the OpenSSL DLL too late in some instances. To fix this, I had to create a new Python wrapper executable in C++, with the following code:

#include "Python.h"
#include "openssl\crypto.h"

auto volatile GetVersionOpenSSL{ &SSLeay };

int wmain(size_t const argc, wchar_t const *const argv[]) {
    Py_Initialize();
    int const result{ Py_Main(argc, const_cast<wchar_t**>(argv)) };
    Py_Finalize();
    return result;
}

请注意,我还必须执行以下其他操作:

Note that I had to take the following additional actions as well:

  1. 添加 libeay32.lib 作为链接器命令行中的第一个库
  2. 禁用链接器优化以删除未使用的引用
  1. Add libeay32.lib as the first library in the linker command line
  2. Disable the linker optimization to remove unused references

使用相同的参数调用生成的可执行文件而不是python.exe,该错误应该消失.

Call the resulting executable instead of python.exe with the same arguments, and that error should go away.

这篇关于Python ctypes dll加载错误487的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 05:57