【问题标题】:Loading DLL results in error 193, even though it can load in both ctypes and JNA加载 DLL 会导致错误 193,即使它可以在 ctypes 和 JNA 中加载
【发布时间】:2021-04-27 21:47:55
【问题描述】:

我正在将 Python 程序移植到 C++(在 Windows 上)。由于所述代码依赖于 DLL,因此我需要加载 DLL。但是,当我调用 LoadLibraryA 指定我的 DLL 的完整路径(带有反斜杠)时,它无法加载并且 GetLastError 返回 193。

这是一个示例程序来演示:

#include <iostream>
#include <windows.h>

using std::cout, std::endl;

int main(int argc, char* argv[]) {
  if (argc != 2) {
    cout << "You only need to specify one argument, path to DLL." << endl;
    exit(2);
  }

  HMODULE dll = LoadLibraryA(argv[1]);
  if (dll == NULL) {
    cout << "DLL at " << argv[1] << " could not be loaded." << endl;
  }
  FreeLibrary(dll);
  return 0;
}

我将我的 DLL 的完整路径(如“C:\path\to\somewhere\test.dll”)指定为第一个命令行参数,但它失败了。为什么它不会加载,即使它在 JNA 和 ctypes 等外部函数接口中加载?

编辑 1:DLL 是 64 位的。

【问题讨论】:

  • 混合 32 位和 64 位?
  • 你的 dll 和可执行文件是为相同的架构构建的吗?
  • Error 193 是 ERROR_BAD_EXE_FORMAT,“%1 不是有效的 Win32 应用程序。”

标签: c++ winapi dll


【解决方案1】:

检查您是在编译 64 位还是 32 位代码的一种简单方法是使用以下代码 (C++17):

#include <iostream>

using std::cout, std::endl;

int main(int argc, char* argv[]) {
  cout << "Your compiler compiled for " << sizeof(void*) * 8 << "-bit systems." << endl;
}

上面的代码通过检查指针的大小来工作。 32 位应用程序使用 4 字节指针,而 64 位应用程序使用 8 字节指针。

编辑:您可以使用dumpbin(Visual Studio 提供)进行检查。见this answer。您还可以使用预处理器宏:

#include <iostream>

using std::cout, std::endl;

int main(int argc, char* argv[]) {
  #ifdef __MINGW64__
  cout << "MinGW-w64" << endl;
  #endif
}

如果它是由 MinGW-w64 编译的,它只会打印"MinGW-w64"。这些方法比我最初使用的指针方法可靠得多。

就我而言,我使用的是 MinGW 而不是 MinGW-w64。因此,生成的 .exe 是一个 32 位应用程序,它与 64 位 .dll 冲突,进而导致错误 193。

【讨论】:

猜你喜欢
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多