0

我有一个使用动态 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然后我循环调用 foo3 100 次;数组arr1得到正确更新,并在 PMAIN 的整个执行过程中“保留”该值,而每次我调用foo3时,数组arr2只包含零,它会被更新,而当程序再次调用foo3时,它又是空白的。PMAIN 如何覆盖 DLL 中数组的地址(我在调试时看到了这种行为)。

你知道这怎么可能?

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

4

1 回答 1

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-> 来访问它的成员。像这样:

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

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

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

于 2011-04-07T13:07:39.067 回答