如何在没有 lib 文件的情况下将 dll 引用到 Visual Studio

2021-12-31 00:00:00 dll c++ visual-studio-2013

我需要在我的项目中添加一个第三方库,而他们只提供了一个 .dll 文件(没有 .lib)

I needed to add a third party library to my project, and they only supply a .dll file (no .lib)

我已通过转到 Common Properties -> References -> Add New Reference 下的项目属性页将 dll 添加到项目中

I have added the dll to the project by going to the project Property Page under Common Properties -> References -> Add New Reference

我可以在解决方案资源管理器中的 External Dependencies 文件夹下看到 dll,所以我猜它被正确包含了.

I can see the dll under the External Dependencies folder in the Solution Explorer, so I guess it was included correctly.

但是我如何引用 dll?当我尝试添加实例变量(例如,MCC::iPort::ASCII iPort)来访问 dll 类时,出现错误:名称后跟::"必须是类或命名空间名称,但我知道那是我可以在外部依赖项下的 dll 信息中看到的类名.

But how do I reference the dll? When I try to add an instance variable (For example, MCC::iPort::ASCII iPort) to access the dll class, I get Error: name followed by '::' must be a class or namespace name, but I know thats the class name I can see it in the dll info under External Dependencies.

推荐答案

访问没有 .lib 文件的裸 DLL 的唯一方法是使用 LoadLibrary(),获取指向要使用 GetProcAddress(),然后将这些指针转换为正确的函数签名.如果库导出 C++ 函数,则必须传递给 GetProcAddress() 的名称将被修改.您可以使用 dumpbin/exports your.dll.

The only way to access a bare DLL without a .lib file is to load the DLL explicitly with LoadLibrary(), get pointers to the exported functions you want to access with GetProcAddress(), and then cast those pointers to the proper function signature. If the library exports C++ functions, the names you have to pass to GetProcAddress() will be mangled. You can list the exported names with dumpbin /exports your.dll.

extern "C" {
    typedef int (*the_func_ptr)( int param1, float param2 );
}

int main()
{
    auto hdl = LoadLibraryA( "SomeLibrary.dll" );
    if (hdl)
    {
        auto the_func = reinterpret_cast< the_func_ptr >( GetProcAddress( hdl, "the_func" ) );
        if (the_func)
            printf( "%d
", the_func( 17, 43.7f ) );
        else
            printf( "no function
" );

        FreeLibrary( hdl );
    }
    else
        printf( "no library
" );

    return 0;
}

正如其他人所指出的,可以创建 LIB 文件.从 dumpbin/exports your.dll 获取导出的函数列表:

As has been noted by others, a LIB file can be created. Get the list of exported functions from dumpbin /exports your.dll:

ordinal hint RVA      name
      1    0 00001000 adler32
      2    1 00001350 adler32_combine
      3    2 00001510 compress
(etc.)

将名称放入 DEF 文件:

Put the names into a DEF file:

EXPORTS
adler32
adler32_combine
compress
(etc.)

现在制作 LIB 文件:

Now make the LIB file:

lib /def:your.def /OUT:your.lib

对于名称已被修饰的情况,无论是通过 C++ 名称修改还是 32 位 stdcall 调用约定,只需复制并粘贴 dumpbin 报告的任何名称,修改和全部.

For cases where the name has been decorated, either by C++ name mangling or 32-bit stdcall calling convention, simply copy and paste whatever names dumpbin reported, mangling and all.

相关文章