DLL中静态创建的数组通过调用Program获取Overwrittend

时间:2011-04-07 12:50:44

标签: c++ dll memory-management overwrite

我有一个使用dinamically DLL的主程序(PMAIN)。假设PMAIN使用DLL导出的2个函数(foo1,foo2和foo3)。功能是这样的:

int __stdcall foo1(){
  str = new MyStruct;
}
int __stdcall foo2(){
  str.LC->objF1();
}

int __stdcall foo3(int val){
  str.LC->objF2(val);
}

MyStruct是这样的:

struct MyStruct{
  MyObject LC
}

MyObject是:

class MyObject{
 private:
  int arr1[100];
  int arr2[100];
  int Index;
 public:
  MyObject();
  ~MyObject();
  void objF1();
  void objF2(int val);
}

void MyObject::objF1(){
  for(int i=0;i<100;i++){
    arr1[i]=1;
  }
}

void MyObject::objF2(int val){
  Index++;
  arr2[Index]=val;
}
MyObject::MyObject(){
  for(int i=0;i<100;i++){
    arr1[i]=0;
    arr2[i]=0;
  }
  Index=-1;
}

从PMAIN我首先调用 foo1 然后 foo2 然后我循环100次调用foo3;数组 arr1 在PMAIN的整个执行期间正确更新并“保留”值,而每次调用 foo3 时,数组 arr2 仅包含它会更新为零,当程序再次调用 foo3 时,它再次为空白。一些PMAIN如何覆盖DLL中数组的地址(我看到这种行为运行调试)。

你知道怎么可能吗?

是不是PMAIN和DLL应该在内存中的两个不同位置?

1 个答案:

答案 0 :(得分:0)

在DLL中创建的变量与程序使用的变量相同,因此如果程序中存在错误,它可以覆盖它们。

这对我来说不对:

int __stdcall foo1(){
  str = new MyStruct;
}
int __stdcall foo2(){
  str.LC->objF1();  
}

int __stdcall foo3(int val){
  str.LC->objF2(val);
}

如果str是指针,(因为你是新手),那么你需要使用operator-&gt;访问它的成员。像这样:

int __stdcall foo1(){
  str = new MyStruct;
}
int __stdcall foo2(){
  str->LC.objF1();
}

int __stdcall foo3(int val){
  str->LC.objF2(val);
}

由于LC不是指针,而只是结构中的自动变量,因此需要使用. operator。如上所述。