草庐IT

c++ - 动态库加载问题

coder 2024-06-18 原文

我正在尝试制作一个非常简单的 Windows 运行时动态库加载示例,但 GetProcAddress() 返回错误,我不明白为什么。


dll_test.cpp:

#include "stdafx.h"
#include "dll_test.h"

static const char* const helloWorldStr = "Hello world!";
static const int age = 25;

DLL_TEST_API const char* helloWorld()
{
    return helloWorldStr;
}

DLL_TEST_API const int getAge()
{
    return age;
}

dll_test.h:

#ifdef DLL_TEST_EXPORTS
#define DLL_TEST_API __declspec(dllexport)
#else
#define DLL_TEST_API __declspec(dllimport)
#endif

DLL_TEST_API const char* helloWorld();
DLL_TEST_API const int getAge();

现在是动态链接代码,dll_dynamic.cpp:

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

typedef const char* (__cdecl *helloWorldFunc)();
typedef const int (__cdecl *getAgeFunc)();

int main()
{
    HMODULE lib = LoadLibrary(L"C:\\VS\\dll_compile\\Release\\dll_test.dll");

    if (lib == NULL)
    {
        fprintf(stderr, "Failed to open lib (%lu)\n", GetLastError());
        return EXIT_FAILURE;
    }

    helloWorldFunc myHelloWorld = (helloWorldFunc) GetProcAddress(lib, "helloWorld");

    if (myHelloWorld == NULL)
    {
        fprintf(stderr, "Failed to open helloWorld() (%lu)\n", GetLastError());
        return EXIT_FAILURE;
    }

    getAgeFunc myGetAge = (getAgeFunc) GetProcAddress(lib, "getAge");

    if (myGetAge == NULL)
    {
        fprintf(stderr, "Failed to open getAge() (%lu)\n", GetLastError());
        return EXIT_FAILURE;
    }

    printf("\"%s\"\n", myHelloWorld());
    printf("age = %d\n", myGetAge());

    if (!FreeLibrary(lib))
    {
        fprintf(stderr, "Failed to free lib (%lu)\n", GetLastError());
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

此代码打印以下内容:

Failed to open helloWorld() (127)

此错误定义为:

ERROR_PROC_NOT_FOUND

127 (0x7F)

The specified procedure could not be found.

我已经使用 objconv 来检查函数是否确实被导出,如果我正确解释了以下内容,我认为它们是:

; Disassembly of file: dll_test.dll
; Sun Nov 15 20:06:06 2015
; Mode: 32 bits
; Syntax: MASM/ML
; Instruction set: 80386

.386
option dotname
.model flat
assume fs:nothing

public ?helloWorld@@YAPBDXZ
public ?getAge@@YA?BHXZ
public Entry_point

extern EncodePointer: near                              ; KERNEL32.dll
extern GetSystemTimeAsFileTime: near                    ; KERNEL32.dll
extern GetCurrentProcessId: near                        ; KERNEL32.dll
extern GetCurrentThreadId: near                         ; KERNEL32.dll
extern GetTickCount: near                               ; KERNEL32.dll
extern QueryPerformanceCounter: near                    ; KERNEL32.dll
extern IsDebuggerPresent: near                          ; KERNEL32.dll
extern SetUnhandledExceptionFilter: near                ; KERNEL32.dll
extern UnhandledExceptionFilter: near                   ; KERNEL32.dll
extern GetCurrentProcess: near                          ; KERNEL32.dll
extern TerminateProcess: near                           ; KERNEL32.dll
extern InterlockedCompareExchange: near                 ; KERNEL32.dll
extern Sleep: near                                      ; KERNEL32.dll
extern InterlockedExchange: near                        ; KERNEL32.dll
extern DecodePointer: near                              ; KERNEL32.dll
extern _except_handler4_common: near                    ; MSVCR100.dll
extern _onexit: near                                    ; MSVCR100.dll
extern _lock: near                                      ; MSVCR100.dll
extern __dllonexit: near                                ; MSVCR100.dll
extern _unlock: near                                    ; MSVCR100.dll
extern __clean_type_info_names_internal: near           ; MSVCR100.dll
extern _crt_debugger_hook: near                         ; MSVCR100.dll
extern __CppXcptFilter: near                            ; MSVCR100.dll
extern _amsg_exit: near                                 ; MSVCR100.dll
extern _initterm_e: near                                ; MSVCR100.dll
extern _initterm: near                                  ; MSVCR100.dll
extern _encoded_null: near                              ; MSVCR100.dll
extern free: near                                       ; MSVCR100.dll
extern _malloc_crt: near                                ; MSVCR100.dll

最佳答案

您需要确保导出的函数名称被视为 C,否则名称会被破坏。你可以这样做:

extern "C" {

    DLL_TEST_API const char* helloWorld()
    {
        return helloWorldStr;
    }

    DLL_TEST_API const int getAge()
    {
        return age;
    }

}

如果您不知道您的 C 头文件是否将在 C++ 中使用,您可以确保您的符号在 C 中导出 linkage通过使用

包装你的头文件
#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}
#endif

关于c++ - 动态库加载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724736/

有关c++ - 动态库加载问题的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  4. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  5. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  6. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  7. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  8. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  9. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  10. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

随机推荐