2013-10-03 82 views
1

我已经开始尝试使用dll并遇到此问题。我有2种溶液(VS 2012) 1.我在哪里产生的DLL(包含:templatedll.h,templatedll.cpp,templatedllshort.h) 2.如我测试(I使用因此templatedllshort.h)运行时检查失败#2 - 变量周围的堆栈已损坏

所以这是我第一次(DLL)的代码解决方案

templatedll.h

class __declspec(dllexport) Echo 
{ 
private: 
    int output; 
    void echo_private(); 

public: 
    Echo(); 
    Echo(int output_); 
    ~Echo(); 
    void echo_public(); 
}; 

templatedll.cpp

#include "templatedll.h" 
#include <iostream> 

Echo::Echo() 
{ 
    output = 0; 
    std::cout << "Echo()\n"; 
} 

Echo::Echo(int output_) 
{ 
    this->output = output_; 
    std::cout << "Echo(int)\n"; 
} 

Echo::~Echo() 
{ 
    std::cout << "~Echo()\n"; 
} 

void Echo::echo_private() 
{ 
    std::cout << "this is output: " << this->output << std::endl; 
} 

void Echo::echo_public() 
{ 
    echo_private(); 
} 

模板llshort.h(这是隐藏我的类的所有私处短头)

class __declspec(dllimport) Echo 
{ 
public: 
    Echo(); 
    Echo(int output_); 
    ~Echo(); 
    void echo_public(); 
}; 

,我测试

#include "templatedllshort.h" 

int main() 
{ 
    Echo e(1); 
    e.echo_public(); 
    return 0; 
} 

一切都正确相连,这两种解决方案编译和运行第二个解决方案。运行时检查失败后返回0;声明。 这是预期的输出:

Echo(int) 
this is output: 1 
~Echo() 

任何一个能看到的问题是什么? 谢谢

+0

我不认为你可以重新定义这样的类,并让它工作。我的意思是你需要在公共和私人标题中使用相同的尺寸。 – drescherjm

回答

1

(这是一个短期头部,它隐藏我的类的所有私有部分)

这是致命的。您的DLL的客户端代码将通过错误的大小到分配器来创建对象。并创建一个太小的对象。在这种特殊情况下,它不会为该对象预留足够的堆栈空间。 DLL本身现在将涂写到未分配的内存。/RTC警告旨在让您摆脱这种麻烦。

不要说谎讲课。

使用接口和工厂函数来隐藏实现细节。

+0

谢谢,我没有考虑过。这解释了它! –

0

我认为你需要为DLL和驱动程序应用程序使用相同的头文件。此外,我没有看到你在驱动程序应用程序中导入DLL的位置。

1

问题来自#include "templatedllshort.h"。你不能“隐藏”这样的私人信息。你能否使用#include "templatedll.h"并检查你是否不再面对这个问题?

+0

我已经尝试过在这里张贴之前,并想知道为什么它的作品,而替代没有。现在我知道 –

0

该类的定义必须在每个源文件中相同,否则它是未定义的行为。

相关问题