dll文件的c++制作
1、首先用vs2005建立一個c++的dll動態鏈接庫文件,這時,
// DllTest.cpp : 定義 DLL 應用程序的入口點。
//
#include "stdafx.h"
//#include "DllTest.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
?????????????????????? DWORD??ul_reason_for_call,
?????????????????????? LPVOID lpReserved
?????????? )
{
????return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
這段代碼會自動生成,
2、自己建一個DllTest.h的頭文件,和DllTest.def的塊聲明文件。
其中頭文件是為了聲明內部函數使用。塊聲明主要是為了在dll編譯成功后固定好方法名。別忘記添加#include "DllTest.h"
3、在DllTest.h中加入如下代碼
#ifndef DllTest_01
#define??DllTest_01
#define EXPORT extern "C" __declspec(dllexport)
//兩個參數做加法
EXPORT int _stdcall Add(int iNum1=0,int iNum2=0);
//兩個參數做減法
EXPORT int _stdcall Subtraction(int iNum1=0,int iNum2=0,int iMethod=0);
#endif
4、在DllTest.def中加入如下代碼
LIBRARY????"DllTest"
EXPORTS
??Add
??Subtraction
5、在DllTest.cpp中寫好代碼為
// DllTest.cpp : 定義 DLL 應用程序的入口點。
//
#include "stdafx.h"
#include "DllTest.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
?????????????????????? DWORD??ul_reason_for_call,
?????????????????????? LPVOID lpReserved
?????????? )
{
????return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
//加函數
int APIENTRY Add(int a,int b)?? // APIENTRY??此關鍵字不可少
{
??return (a+b);
}
//減函數
int APIENTRY Subtraction(int a,int b,int i)
{
??if(0==i)
????return (a-b);
??else
????return (b-a);
}
6、這樣編譯生成就可以得到對應的DllTest.dll的文件了
二、C#調用dll文件
1、創建一個c#的控制臺程序(當然其他也沒有問題),自動生成以下代碼
using System;
using System.Collections.Generic;
using System.Text;
//using System.Runtime.InteropServices;
namespace CSharpIncludeC__Dll
{
????class Program
????{
????????static void Main(string[] args)
????????{
????????}
????}
}
2、添加命名空間using System.Runtime.InteropServices;
3、若要引用dll文件,首先吧dll文件自行拷貝到bin/debug,文件夾下,沒有的話,先編譯一下。
4、添加屬性
[DllImport("DllTest.dll", CharSet = CharSet.Ansi)]
static extern int Add(int iNum1, int iNum2);
5、最終產生代碼
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace CSharpIncludeC__Dll
{
????class Program
????{
????????[DllImport("DllTest.dll", CharSet = CharSet.Ansi)]
????????static extern int Add(int iNum1, int iNum2);
????????[DllImport("DllTest.dll", CharSet = CharSet.Ansi)]
????????static extern int Subtraction(int iNum1,int iNum2,int iMethod);
????????static void Main(string[] args)
????????{
????????????int iValue = Add(1, 2);
????????????Console.WriteLine(iValue);
????????????iValue = Subtraction(1, 2, 1);
????????????Console.WriteLine(iValue);
????????????Console.Read();
????????}
????}
}
6、生成項目運行就可以了,結果是3和1