0

我有一个当前位于 .lib 文件中的类:

class __declspec(dllexport) ReportData {
public:
        list<FileData *> ReportFileData;
        list<SupressionData *> ReportSupressionData;

        static char *ClientName;
        static char *DataRecieved;

        std::string GenFileConfTemplate();

        ~ReportData()
        {
                ReportFileData.clear();
                ReportSupressionData.clear();
        }

};

我可以将此 lib 文件添加到我的项目中并创建此类的实例没问题。我的问题是,如何将它移动到 DLL 并动态加载它,并创建此类的实例。我想要做的是将一些常用功能移到这个 dll 中,并在多个项目中共享。

如果需要,我希望能够在进行更改时重新编译 dll,并让项目使用必须的最新版本;到目前为止,使用 lib,我必须在重新编译 dll 后重新编译每个项目才能进行更改,并且由于这个系统最初的设计方式,有 100 多个项目将使用这个 lib/dll,而我不想在每次更改时重新编译 100 个不同的项目。

所以,请给我你的专家意见,我应该如何去做。

我将在我的项目中使用 dll,如下所示:

    ReportData *rd = new ReportData();

    ReportData::ClientName = "test";

    rd->ReportFileData.push_back(new  FileData("testing", 10, 1));
    rd->ReportFileData.push_back(new  FileData("testing 2", 20, 1));

    std::cout << rd->GenFileConfTemplate();

    delete rd;

我最终得到了这样的结果:

typedef Foo* (__stdcall *CreateFunc)();

int main()
{
        HMODULE dll (LoadLibrary ("..\\LLFileConfirmDLL\\LLFileConfirmDLL.dll"));
        if (!dll) {
                cerr << "LoadLibrary: Failed!" << endl;
                std::cin.get();
                return 1;
        }

        CreateFunc create (reinterpret_cast<CreateFunc>(GetProcAddress (dll, "create")));
        if (!create) {
                cerr << "GetProcAddress: Failed!" << endl;
                std::cin.get();
                return 1;
        }

        Foo *f = create();
        cerr << f->Test();


        FreeLibrary (dll);

        std::cin.get();

        return 0;
}

struct FOOAPI Foo
{
        Foo();
        virtual ~Foo(); 
    virtual int Test();
};

Foo::Foo()
{
}

Foo::~Foo()
{
}

int Foo::Test()
{
        return 5;
}

extern "C" __declspec(dllexport) Foo* __stdcall create()
{
        return new Foo;
}
4

1 回答 1

2

您可以按照 COM 的方式执行此操作:

  1. 导出一个 CreateInstance() 函数。
  2. 将 void** 和唯一标识符传递给 CreateInstance()。
  3. 您的消费 DLL 调用库 DLL 上的 LoadLibrary() 并调用 CreateInstance()。
  4. CreateInstance() 执行新的 ReportData 并在 void** out 参数中返回它。

编辑:

就像是:

extern "C"
BOOL CreateObject(REFCLSID rclsid, void** ppv) {
    BOOL success = false;
    *ppv = NULL;
    if (rclsid == CLSID_ReportData) {
        ReportData* report_data = new ReportData();
        if (report_data) {
            *ppv = report_data;
            success = true;
        }
    } else if (...) {
        ... other objects ...
    }
    return success;
}

当然,现在您必须担心诸如谁将释放对象、确保 DLL 不会被卸载等问题。

另请参见DllGetClassObjectDllCanUnloadNow等。

于 2009-06-22T14:18:11.393 回答