如何从主项目C 加载DLL

How to load the DLL from the main project c++

本文关键字:加载 DLL 项目      更新时间:2023-10-16

我创建了一个使用2个dll互相对抗的项目(dll是播放器)。游戏是第一个玩家选择了一个数字,第二个玩家选择了另一个数字,然后PlayRound功能比较了两个数字。我的问题不确定如何加载DLL(运行/加载时间)。我创建了我的第一个DLL(Simple.dll),其挑选函数总是返回" int 2",以简单:

#include "stdafx.h"
#define ASEXPORT
#include <iostream>
#include "player.h"
using namespace std;
int Pick(int Round, int MyMoves[], int OpponentMoves[])
{
    return 2;
}

这个项目具有带有以下代码的标题(player.h):

#ifndef ASEXPORT
#define DLLIMPORTOREXPORT dllimport
#else
#define DLLIMPORTOREXPORT dllexport
#endif
_declspec(DLLIMPORTOREXPORT) int Pick(int Round, int MyMoves[], int OpponentMoves[]);

不确定在哪里包含此代码,我是否将其包括在主或函数中:

    HINSTANCE hinstLib; 
    MYPROC ProcAdd; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 
    // Get a handle to the DLL module.
    //hinstLib = LoadLibrary(TEXT(player2Name)); 
    hinstLib = LoadLibrary();
    // If the handle is valid, try to get the function address.
    if (hinstLib != NULL) 
    { 
        ProcAdd = (MYPROC) GetProcAddress(hinstLib, "simple.DLL"); 
        // If the function address is valid, call the function.
        if (NULL != ProcAdd) 
        {
            fRunTimeLinkSuccess = TRUE;
            (ProcAdd) (L"Message sent to the DLL functionn"); 
        }
        // Free the DLL module.
        fFreeResult = FreeLibrary(hinstLib); 
    } 
// Report any failures
    if (! fRunTimeLinkSuccess) 
        printf("Unable to load DLL or link to functionsn"); 
    if (! fFreeResult) 
        printf("Unable to unload DLLn");
//

我希望我很容易理解

您可以在我的ModuleService实现中在Indiezen Core库中看到这一点。我将.dll和.So视为"模块"。在我的插件系统中,我有一个标准,每个模块都实现一个和仅一个导出的功能,这是我示例中getModule()Pick(),在您的用例中。

我的示例返回I_Module接口的实现。在我的示例中,模块是插件的集合,因此您唯一可以做的就是获得I_plugin的实现,而I_plugin又可以用于访问类工厂,然后这些类别的工厂构造对象(扩展)预定义的接口(扩展点)。

我知道这对您的示例来说都是过分的,但是代码很容易遵循。可以随意复制/粘贴可以使用的子集。

一个关键是不要在Pick函数上使用_declspec(DLLIMPORTOREXPORT);您应该只导出该功能而不导入该功能。您也不应该将这些DLL链接到您的主要应用程序,也不应将DLL的标题文件包含在主应用程序中。这将使您的灵活性能够导入两个单独的DLL,它们在没有链接错误的情况下揭示相同功能(Pick)。它还将为您提供不知道DLL名称之前的优势(在此可能您可能希望某些配置或GUI让用户选择哪个玩家)。

我的实现,带有参考计数,班级工厂等,将为您带来额外的优势,因为您可以在同一DLL中实现两个玩家。