1。編寫(xiě)DLL
a)文件--打開(kāi)--新建項(xiàng)目--Win32,右側(cè)Win32項(xiàng)目,填寫(xiě)好項(xiàng)目名稱(chēng),點(diǎn)擊“下一步”,
應(yīng)用程序類(lèi)型選擇:“DLL(D)”,附加選項(xiàng):空項(xiàng)目(E),然后完成。
b)編寫(xiě)頭文件(edrlib.h):
#ifdef __cplusplus
#define EXPORT extern "C" __declspec (dllexport)
#else
#define EXPORT __declspec (dllexport)
#endif
EXPORT void EdrCenterTextA();
EXPORT void EdrCenterTextW();
EXPORT int IncCounter();
#ifdef UNICODE
#define EdrCenterText EdrCenterTextW
#else
#define EdrCenterText EdrCenterTextA
#endif
注解:
i. 定義 __cplusplus表示是供C++程序中調(diào)用。
ii.__declspec (dllexport)表示函數(shù)調(diào)用方式,此處表示VS2008工程屬性調(diào)用的默認(rèn)方式。更改方法:
右擊項(xiàng)目--屬性--配置屬性--C/C++--高級(jí),更改右側(cè)“調(diào)用約定”。
c)編寫(xiě)DLL文件(edrlib.cpp):
#include "windows.h"
#include "edrlib.h"
//counter供調(diào)用該DLL的所有應(yīng)用程序共享
#pragma data_seg("shared")
int counter=0;
#pragma comment(linker,"/SECTION:shared,RWS")
int WINAPI DllMain(_In_ HANDLE _HDllHandle, _In_ DWORD _Reason, _In_opt_ LPVOID _Reserved)


{
return TRUE;
}
EXPORT void EdrCenterTextA()


{
MessageBox(NULL,TEXT("調(diào)用DLL函數(shù)!"),TEXT("ASSIC版本"),MB_OK);
}
EXPORT void EdrCenterTextW()


{
MessageBox(NULL,TEXT("調(diào)用DLL函數(shù)!"),TEXT("UNICODE版本"),MB_OK);
}
EXPORT int IncCounter()


{
return ++counter;
}
c)編譯生成DLL。
2。調(diào)用DLL
方法一、
1。新建Win32應(yīng)用程序空項(xiàng)目。
2。把生成的dll、lib這2個(gè)文件復(fù)制到新建的目錄下。
3。添加導(dǎo)入庫(kù):工具--項(xiàng)目和解決方案--VC++目錄,選擇右側(cè)“顯示以下內(nèi)容的目錄”下的“庫(kù)文件”,把lib所在目錄添加。
4。頭文件:edrlib.h(與編寫(xiě)DLL中一樣)
5。源文件:main.c

/**//*#define cplusplus*/ //c++調(diào)用方式
#include "windows.h"
#include "edrlib.h"
#pragma comment(lib,"edrlib.lib")
int WINAPI WinMain(__in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd )


{
TCHAR buf[32];
wsprintf(buf,L"now,counter=%i",IncCounter());
MessageBox(NULL,buf,L"--",MB_OK);
EdrCenterText();
return 0;
}

解釋?zhuān)?
可注釋#pragma comment(lib,"TestDLL2.lib")這條,但必須設(shè)置鏈接庫(kù),方法:
右擊項(xiàng)目--屬性--配置屬性--鏈接器--輸入--附加依賴(lài)項(xiàng):edrlib.lib
6.運(yùn)行測(cè)試成功。
【以上內(nèi)容轉(zhuǎn)自:http://blog.csdn.net/breezes2008/archive/2010/02/25/5326861.aspx】
3、在C#中調(diào)用DLL
此示例使用 C 程序創(chuàng)建一個(gè) DLL,在下一示例中將從 C# 程序調(diào)用該 DLL。
// cmdll.c// Compile with: /LDint __declspec(dllexport) SampleMethod(int i){ return i*10;}
如果是Web項(xiàng)目,把DLL復(fù)制到bin目錄下。
如果是桌面程序,把DLL復(fù)制到可執(zhí)行行文件目錄下。
引用代碼:

using System;using System.Runtime.InteropServices;public class MainClass
{ [DllImport("Cmdll.dll")] public static extern int SampleMethod(int x); static void Main()
{ Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5)); }}
from:http://apps.hi.baidu.com/share/detail/33471191
posted on 2011-05-08 10:41
mr_chen 閱讀(3589)
評(píng)論(1) 編輯 收藏 引用 所屬分類(lèi):
C#開(kāi)發(fā)筆記