// ifaststring.h//
class _declspec(dllexport)IFastString
{
public:
virtual void Delete(void) = 0;
virtual int Length(void) = 0;
virtual int Find(const char *psz) = 0;
};
extern "C"
IFastString *CreateFastString(const char *psz);
// ifaststring.h //
#include"ifaststring.h"
class FastString:public IFastString
{
private:
const int m_cch; //number of character
char *m_psz;
public:
FastString(const char *psz);
~FastString(void);
int Length(void);
int Find(const char *psz);
void Delete(void);
};
// faststring.cpp//
#include<string>
#include"faststring.h"
IFastString *CreateFastString(const char *psz)
{
return new FastString(psz);
}
FastString::FastString(const char* psz):m_cch(strlen(psz)),
m_psz(new char[strlen(psz)+1])
{
strcpy(m_psz, psz);
}
FastString::~FastString(void)
{
delete[] m_psz;
}
void FastString::Delete(void)
{
delete this;
}
int FastString::Length(void)
{
return m_cch;
}
int FastString::Find(const char *psz) //the function is not complete
{
return 1;
}
// mainTest.cpp//
#include"ifaststring.h"
#include<iostream>
using namespace std;
int f(void)
{
int n = -1;
IFastString *pfs = CreateFastString("Hi Bob");
if( pfs->Find("g") )
{
cout<<" test success! "<<endl ;
}
return 2;
}
int main( )
{
int m;
m = f();
cout<<m;
return 0;
}
在Faststring.DLL中,除了一个入口函数之外,其它所有入口函数都是虚函数。接口类的虚函数总是通过保存在vbtl中的函数指针被间接调用,客户程序不需要在开发的时候链接这些函数的符号名。青年人网提示这意味着接口方法可以不受“不同编译器之间符号名改编方式的不同的影响”。唯一需要通过名字显式链接的入口函数是CreateFastString,这个全局函数使得客户可以进入到FastString的世界中。这个函数使用extern “c”被引出,从而避免了符号名改编方式的冲突。这也隐含着所有的C++编译器都期盼引入库和DLL引出同样的符号。 使用这项技术的一个直接结果是, 我们可以安全的在一个C++环境中暴露DLL中的类,并且在另一个C++开发环境中访问这个类。对于建立一个与编译器厂商无关的可重用组件来说 ,这种能力是非常重要的!
责任编辑:小草