【问题标题】:DLL import failure in using WinDivert使用 WinDivert 时 DLL 导入失败
【发布时间】:2014-08-08 14:34:18
【问题描述】:

我将设计一个使用 WinDivert 来控制网络流量的程序。 我使用的语言是 C++,程序是在 Visual Studio 2008 下设计的。 首先,我在 Visual C++ CLR(Windows 窗体应用程序)中创建了一个项目,这样我就可以简单地实现 UI。

为了导入WinDirvert库,我在项目属性中做了如下设置:

  1. 配置属性:常规
    公共语言运行时支持:公共语言运行时支持(/ctr)
  2. 配置属性:链接器
    附加依赖:WinDivert.lib 的链接
    模块定义文件:windivert.def 的链接

在我创建的项目中,我还在头文件中添加了 windivert.h。

另外,windivert.h 包含在我的项目 (ProjectG.cpp) 的主入口点中:

#include "stdafx.h"
#include "Form1.h"
#pragma managed(push, off)
#include "windivert.h"
#pragma managed(pop)

using namespace ProjectG;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Enabling Windows XP visual effects before any controls are created
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    // Create the main window and run it
    Application::Run(gcnew Form1());


    HANDLE handle;
    unsigned char packet[8192];
    UINT packet_len;
    WINDIVERT_ADDRESS addr;
    handle = WinDivertOpen("udp", WINDIVERT_LAYER_NETWORK, 0,
        WINDIVERT_FLAG_DROP);
    if (handle == INVALID_HANDLE_VALUE)
    {
        Application::Exit();        
    }
    while (TRUE)
    {
        // Read a matching packet.
        if (!WinDivertRecv(handle, packet, sizeof(packet), &addr, &packet_len))
        {
            MessageBox::Show("Fail");
            continue;
        }
    }
    return 0;
}

最后我把{WinDivert.dll, windivert.h, WinDivert.lib, WinDivert32.sys}放到了项目目录下。

但是,显示以下错误:

fatal error LNK1306: DLL entry point "int __clrcall main(cli::array<class
System::String ^ >^)" (?main@@$$HYMHP$01AP$AAVString@System@@@Z) cannot be managed;    
compile to native   ProjectG.obj    ProjectG

附加:(警告)

warning LNK4070: /OUT:WinDivert.dll directive in .EXP differs from output filename   
'C:\Users\David\Desktop\css\ProjectG\Debug\ProjectG.exe'; ignoring directive    
ProjectG.exp    ProjectG

问题: 我该如何解决这种情况?

【问题讨论】:

  • 这是一个完整的火车残骸。不仅编译器和链接器设置严重错误,还在程序终止前一微秒转移了调用。不要尝试在 .NET 程序中执行此操作。
  • @HansPassant 我为 WinDivert 编写了一个 .net 包装器,现在我害怕你看到它的那一天。大声笑

标签: c++-cli dllimport unmanaged wfp


【解决方案1】:

a) 您的主要来源是 .cpp,因此您可以删除 [STAThreadAttribute] 并将
int main(array&lt;System::String ^&gt; ^args) 更改为 int _tmain(int argc, _TCHAR* argv[])

b) 从链接器模块定义文件中排除 windivert.def,仅当您创建 DLL 时才这样做

c) DLL/SYS 文件需要复制到 Debug 和 Release 文件夹

【讨论】:

  • 排除windivert.def后显示更多错误,均为LNK 2028和LNK 2019,表示存在未解决的外部符号“extern "C" int_cdecl...
  • 如果您确实将 WinDivert.lib 添加到链接器输入“附加依赖项”,则“未解决的外部”错误指向函数声明(通常在 .h 文件中)和函数实现之间的差异在 .lib 文件中
  • 感谢问题解决了,最后发现WinDivert WDDK中找到的.lib与Visual Studio不兼容。然后,我在另一个 winDivert 包 (MSVC) 中使用 .lib,它可以工作。
猜你喜欢
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 2021-07-25
  • 2021-04-17
  • 2010-11-06
  • 1970-01-01
相关资源
最近更新 更多