【问题标题】:access static variables/functions in a statically linked library from a dynamic dll从动态 dll 访问静态链接库中的静态变量/函数
【发布时间】:2011-04-25 17:27:36
【问题描述】:

我正在尝试在动态加载的 dll 中使用静态类变量和函数,它们是原始类的子类。这些静态成员用于静态链接的类;这个类使用工厂加载 dll,这些 dll 应该可以访问静态函数和变量。这是一个简短的示例作为简单的演示(即,不要指望它能够编译;实际的类每个都有超过 1000 行):

//GenericBase.h-------------------------
#include "GenericDll.h"
class GenericBase{
public:
   GenericBase()
   {
      mClassA.addInstance(this);
   }
   static int mNumInstances;
   static void DoSomething();
   static void Foo();
   static void LoadDlls();
   set<GenericDll*> mPlugins;
};
//--------------------------------------

//GenericDll.h--------------------------
class GenericDll : public GenericBase
{
    void Function();
};
extern "C" __declspec (dllexport) GenericDll* CreateModule()
{
    GenericDll * module = new GenericDll();
    return module;
}
//--------------------------------------

//GenericBase.cpp-----------------------
void GenericBase::DoSomething()
{
    for (it = mPlugins.begin(); it != mPlugins.end(); it++)
        it->Function();
}
//--------------------------------------

//GenericDll.cpp------------------------
void GenericDll::Function()
{
    mNumInstances++; // mNumInstancesin GenericDll and mNumInstances in
                    // the static linked GenericBase have different
                    // addresses
    cout << &mNumInstances<<endl;

    Foo();          // again, the address Foo() is different in the dll
}
//--------------------------------------

//main.cpp
int main(){
    GenericBase g;
    GenericBase::LoadDlls(); //not shown
    GenericBase::DoSomething();
    cout << &mNumInstances << endl;
}

//Output: these are the addresses of the mNumInstances
>> 00FAC3B0
>> 0F753398
>> 004D3398

所以,总体的问题或目标是:我怎样才能使静态链接对象的 mNumInstances 的地址与该对象子类的动态加载的 dll 类相同?

希望这足够清楚,并且有意义!

【问题讨论】:

  • 基本上,你不能。 DLL 并非旨在成为共享数据的一种方式。
  • 为什么不在你的基础中为你的静态数据提供访问器方法并使数据成员正确地私有?最坏的情况,只需向它添加一个“int * getNumInstancesPtr()”......尽管它的非封装做法很糟糕。根据您的子类想要对数据执行的操作,更合适的一组函数将是 incrementInstanceCount()/decrementInstanceCount() 之类的......

标签: c++ variables dll static subclass


【解决方案1】:

要实现您想要做的,您需要将共享(每个 DLL 复制)静态库设为 DLL 本身。

将 DLL 视为更像一个 EXE。

此外,在返回 set (无论它是什么)之类的内容时,请注意库版本以及编译器和链接器设置,因为对齐、数据类型大小和不同的库实现(从调试到发布)可能意味着运行时错误(如果幸运的话会崩溃)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2015-07-10
    • 2015-07-22
    • 2012-06-29
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多