在 Microsoft Visual C++ 6.0 中製作 DLL



示例 1:使用命令列

現在製作一個單行 DLL。以下是原始碼

extern "C" __declspec(dllexport) void myfun(int * a){*a = - *a; }

將其儲存到檔案 myfun.cpp,然後從 DOS 提示符使用以下命令進行編譯

cl -LD myfun.cpp

-LD 開關用於生成 DLL。接下來,製作一個可執行檔案,該檔案呼叫 DLL。以下是原始碼

#include iostream.h

extern C __declspec(dllimport) void myfun ( int * a);

void main(void)
{
   int a = 6;
   int b = a;
   myfun(&b);

   cout << '-' << a << " is " << b << "! \n";
}

將其儲存到檔案 main.cpp。然後從命令提示符使用以下命令進行編譯和連結

cl main.cpp /link myfun.lib

從命令列執行它(只需鍵入“main”)。

示例 2:使用 VC++ IDE 建立 DLL

在 Microsoft Visual C++ 6.0 中,可以透過選擇 Win32 動態連結庫專案型別或 MFC AppWizard (dll) 專案型別來建立 DLL。

以下程式碼是一個使用 Win32 動態連結庫專案型別在 Visual C++ 中建立的 DLL 示例。

// SampleDLL.cpp

#include "stdafx.h"
#define EXPORTING_DLL
#include "sampleDLL.h"

BOOL APIENTRY DllMain(HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
   return TRUE;
}

void HelloWorld()
{
   MessageBox( NULL, TEXT("Hello World"), TEXT("In a DLL"), MB_OK);
}
// File: SampleDLL.h

#ifndef INDLL_H

   #define INDLL_H

   #ifdef EXPORTING_DLL
      extern __declspec(dllexport) void HelloWorld();
   #else
      extern __declspec(dllimport) void HelloWorld();
   #endif

#endif
dll_examples.htm
廣告
© . All rights reserved.