MFC DLL如何导出类笔记

    在VC上new一个名为dll的MFC DLL工程。

     第一步,创建一个interface.h文件来定义接口,代码如下:

    //file interface.h

    #ifndef _INTERFACE_H_

   #define _INTERFACE_H_

    interface ITest

    {

        virtual int Print()=0;

        virtual ~ITest(){};

    };

    ITest* DllCreateTest();

    void DllDestroyTest(ITest *pTest);

   #endif

   第二步,定义一个继承自接口interface的类CTest,代码如下:

   //file test.h

    #ifndef _TEST_H_

   #define _TEST_H_

   #include "interface.h"

   class CTest : public ITest

   {

   public:

      CTest();

      virtual ~CTest();

      int Print();

   }

   #endif

   //file test.cpp

   #include "StdAfx.h"     //注意这里需要包含这个头文件,否则会报fatal error C1010: unexpected end of file while

                                         // looking for precompiled header directive

   #include "test.h"

    CTest::CTest()

   {

   }

   CTest::~CTest()

   {

   }

   int CTest::Print()

   {

      printf("ok!/n");

      return 0;

   }

   第三步,在dll.cpp文件里,实现DllCreateTest和DllDestroyTest两个函数,代码如下:

   //file dll.cpp

   ......

   ITest* DllCreateTest()

  {

      return new CTest();

   }

   void DllDestroyTest(ITest *pTest)

   {

      if(pTest != NULL) delete pTest;

      pTest = NULL;

   }

   第四步,也是最容易忽略的一步,等以上操作都完成之后,还要在dll.def文件里,把要导出的函数DllCreateTest和DllDestroyTest加进去,如下:

; dll.def : Declares the module parameters for the DLL.

LIBRARY      "dll"
DESCRIPTION  'dll Windows Dynamic Link Library'

EXPORTS
    ; Explicit exports can go here
 DllCreateTest
 DllDestroyTest

  至此,MFC DLL的工程已经完成。那么如何在其他工程中调用生成的dll呢?

   首先,将interface.h文件拷贝到新工程,并将生成dll.dll文件拷贝到新工程的执行路径下;

   其次,在新工程的Project->Settings->Link->Object/library modules设置生成的dll.lib的路径,如:../dll/Debug/dll.lib

  现在,你就可以调用dll中的类了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值