将一个dll的Class对象传递给另一个dll c ++

时间:2014-09-05 12:11:32

标签: c++ dll void-pointers dllexport

我正在努力解决以下情况

我的A.dll正在加载B.dll,并使用A.dll中存在的类对象的指针作为加载函数的参数来调用它的函数

使用该对象引用我可以从B.dll调用A.dll的函数吗?

我的B.dll功能如下,

bool LogManagerThread::StartLogThread(void* AObj)
{
    A* pobj;
    pobj = (A*)AObj;
    pobj->PrintTestMsg();
    return true;
}

' A'是A.dll中的类

如果我以这种方式调用,我将链接错误作为"未解析的外部符号" ..其中PrintTestMsg()是"类A"中的方法。 A.dll

Error 11 error LNK2001: unresolved external symbol "public: void __thiscall A::PrintTestMsg(void)" (?PrintTestMsg@A@@QAEXXZ) D:\ilrewrite2\ConsoleApplication1\LogManager.obj LogMa‌​nager

1 个答案:

答案 0 :(得分:1)

根据你的描述:“我的A.dll正在加载B.dll并调用它的函数参考”,所以A依赖于B,现在你想在B DLL中使用A dll的类,这意味着你有让B依赖于A,所以它创建一个循环,你不能以这种方式实现dll。

实现此目的的一种方法是:在B DLL中实现一组接口,而在A DLL中,A实现这些接口,所以它看起来像这样:

//in B DLL

class BInterface
{
    public:        
        virtual void PrintTestMsg() = 0;
};

   //in A DLL,

   class AChild : public BInterface
{
    public:
        virtual void PrintTestMsg()
        {
            //do stuff
        }
};

作为B DLL中的函数:

bool LogManagerThread::StartLogThread(BInterface* AObj)
{
   if (!AObj)
     return false;

    AObj->PrintTestMsg();
    return true;
}

这些类型应该通过设计来解决,而不是依赖于类,你应该让类依赖于接口来打破依赖。 inversion of control是解决这些问题的模式。

相关问题