C++:dll 不适用于 Visual Studio 2017,但适用于 g++

标签 c++ visual-studio dll visual-studio-2017 g++

我在使用更复杂的代码时遇到了这个问题,这自然是一个简化的示例。
dll 不适用于 VS,但适用于 g++,
我有这个代码,

#include <stdio.h>      

extern "C" __declspec(dllexport) void func(int a)
{
    printf("a: %d\n", a);
}
这是我的 VS 项目中唯一的文件。我编译它,VS成功生成了一个test.dll
Configuration Manager
但是当我调用库(例如从python)时,它提示dll不是win32,看,
import os
import sys
import ctypes
import sys

file_dll = 'test.dll'
print('Using {}...'.format(file_dll),flush=True)
lib = ctypes.cdll.LoadLibrary(file_dll)
a=ctypes.c_int(0)
lib.func(a)
输出,
    Using ./test.dll...
Traceback (most recent call last):
  File "call.py", line 14, in <module>
    lib = ctypes.cdll.LoadLibrary(file_dll)
  File "..\anaconda3\lib\ctypes\__init__.py", line 434, in LoadLibrary
    return self._dlltype(name)
  File "..\anaconda3\lib\ctypes\__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application
现在,如果我使用编译相同的代码,
g++ test.cpp -shared -o test2.dll
输出,
Using test2.dll... a: 0
有人知道我在做什么错吗?

最佳答案

错误“不是有效的 Win32 应用程序”通常表示位不匹配,其中 64 位进程尝试加载 32 位库,或相反。鉴于发布的屏幕截图显示 DLL 是 32 位(平台 = x86),python 模块可能是 64 位的。
错误消息的“Win32 应用程序”部分没有提到引用的模块是 32 位的(在这种情况下确实是)。相反,“Win32 应用程序”是( native )Windows 应用程序的技术术语,与 Windows 主机或客户端应用程序的位数无关。引用 MS 来自 Win32 (Windows API) :

The Win32 API (also called the Windows API) is the native platform for Windows apps. This API is best for desktop apps that require direct access to system features and hardware. The Windows API can be used in all desktop apps, and the same functions are generally supported on 32-bit and 64-bit Windows.

关于C++:dll 不适用于 Visual Studio 2017,但适用于 g++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64827776/

相关文章:

c++ - 链接++ 运算符

c++ - 在 MSVC 中强制未对齐的位域打包

c# - 在属性网格中创建可扩展组?

python 永远不能调用包含继承逻辑的 c++ dll 或 so 文件?

c++ - 当您的外部 SDK 只有.dll、.lib、.h 文件时如何链接和构建项目

c++ - 对于 notepad++ 的 c++ 调试器有什么建议吗?

c++ - 从构造函数传递给成员函数时,私有(private)成员变量为空

c# - 如何使用 WSDL 文件在 Visual Studio.NET 中创建 Web 服务?

c++ - 在 MVS 2010 的 C++ dll 中 try catch block

python - 如何将单个 PyObject(在 C++ 后端创建)传递给嵌入式 Python 解释器?