http://blog.youkuaiyun.com/peter1983/article/details/2898046
1、C++编写的DLL代码如下:
该Dll的功能比较简单,就是实现一个整数加法;
IAddBase 是一个抽象类,IAdd实现了IAddBase的方法,并采用了单例模式;
GetAddInstance()为dll对外的接口,返回一个IAdd的对象指针;
调用者使用该实例就可以调用Add方法
- class IAddBase
- {
- public:
- int virtual __stdcall Add(int a, int b) = 0;
- };
- class IAdd : public IAddBase
- {
- private:
- static Idd* m_Instance;
- protected:
- IAdd(){}
- ~IAdd()
- {
- if (m_Instance != NULL)
- delete m_Instance;
- }
- public:
- int __stdcall Add(int a, int b)
- {
- return a + b;
- }
- static IAdd* GetAddInstance()
- {
- if (m_Instance == NULL)
- m_Instance = new Idd();
- return m_Instance;
- }
- };
- Idd* IAdd::m_Instance = NULL;
- extern "C" __declspec(dllexport) IAddBase* GetAddInstance()
- {
- return Idd::GetAddInstance();
- }
2、在Delphi下调用该Dll,这里采用静态调用方法
- //在type中声明IAddBase,相当于C++中的.h 文件
- Type
- IAddBase = class
- public
- function Add(a, b : Integer):Integer;virtual;stdcall;abstract;
- end;
- function GetAddInstance : IAddBase ; cdecl ; external 'TestAdd.dll';
- var
- myAdd : IAddBase;
- implemetation
- //调用IAddBase中的Add方法
- function DoAdd(a,b:Integer):Integer;
- begin
- myAdd := GetAddInstance;
- result := myAdd.Add(a,b);
- end;
3、注意的问题
3.1 dll和delphi 定义的类函数需要声明为stdcall,有疑问可以Google关键字:Delphi C++ stdcall
3.2 函数重载问题
如果在c++的dll中定义了一个具有相同函数名的类,则在Delphi中无法保证调用正确的函数,这里要指出的是即使在定义时
声明该函数为overload也无法保证正确调用dll中的对应函数
3.3函数定义的顺序
Delphi中定义的类函数的顺序必须和C++ .h文件中定义的类函数顺序保持一致,否则调用将会出错。