(原文:http://blog.chinaunix.net/u/18297/showart_296028.html)
為了能用上原來的C++代碼,只好研究下從C# 中調用DLL
首先必須要有一個聲明,使用的是DllImport關鍵字:
包含DllImport所在的名字空間
using System.Runtime.InteropServices;
public class XXXX{
[DllImport(“MyDLL.dll")]
public static extern int mySum (int a,int b);
}
[DllImport(“MyDLL.dll")]
public static extern int mySum (int a,int b);
代碼中DllImport關鍵字作用是告訴編譯器進入點在哪裡,並將打包函數捆綁在這個類中
在調用的時候
在類中的時候 直接 mySum(a,b);就可以了
在其他類中調用: XXXX. mySum(a,b);
[DllImport(“MyDLL.dll”)]在申明的時候還可以添加幾個屬性
[DllImport(“MyDLL.dll", EntryPoint=" mySum ",CharSet=CharSet.Auto,CallingConvention=CallingC
檔案:
PInvoke.rar
大小:
2790KB
下載:
下載
onvention.StdCall)
]
EntryPoint: 指定要調用的 DLL 進入點。預設進入點名稱是託管方法的名稱 。
CharSet: 控制名稱重整和封送 String 參數的方式 (預設是UNICODE)
CallingConvention指示進入點的函數呼叫慣例(預設WINAPI)(上次報告講過的)
SetLastError 指示被呼叫者在從屬性化方法返回之前是否調用 SetLastError Win32 API 函數 (C#中預設false )
int 類型
[DllImport(“MyDLL.dll")]
//返回個int 類型
public static extern int mySum (int a1,int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int a2,int b2)
{
//a2 b2不能改變a1 b1
//a2=..
//b2=...
return a+b;
}
//參數傳遞int 類型
public static extern int mySum (ref int a1,ref int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int *a2,int *b2)
{
//可以改變 a1, b1
*a2=...
*b2=...
return a+b;
}
DLL 需傳入char *類型
[DllImport(“MyDLL.dll")]
//傳入值
public static extern int mySum (string astr1,string bstr1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr2,char * bstr2)
{
//改變astr2 bstr 2 ,astr1 bstr1不會被改變
return a+b;
}
DLL 需傳出char *類型
[DllImport(“MyDLL.dll")]
// 傳出值
public static extern int mySum (StringBuilder abuf, StringBuilder bbuf );
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr,char * bstr)
{
//傳出char * 改變astr bstr -->abuf, bbuf可以被改變
return a+b;
}
DLL 回呼函數
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)
using System;
using System.Runtime.InteropServices;
public delegate bool CallBack(int hwnd, int lParam); //定義委託函數類型
public class EnumReportApp
{
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);
public static void Main() {
CallBack myCallBack = new CallBack(EnumReportApp.Report); EnumWindows(myCallBack, 0);
}
public static bool Report(int hwnd, int lParam)
{
Console.Write("Window handle is ");
Console.WriteLine(hwnd); return true;
}
}
DLL 傳遞結構 (見代碼)
BOOL PtInRect(const RECT *lprc, POINT pt);
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}
[StructLayout(LayoutKind.Explicit)]
public struct Rect
{
[FieldOffset(0)] public int left;
[FieldOffset(4)] public int top;
[FieldOffset(8)] public int right;
[FieldOffset(12)] public int bottom;
}
Class XXXX {
[DllImport("User32.dll")]
public static extern bool PtInRect(ref Rect r, Point p);
}
DLL 回呼函數,傳遞結構 想看的msdn裡面都有專題介紹,看的我都是暈暈的:)
其他參考請搜尋:
在C#程式設計中使用Win32類庫
C#中調用C++託管Dll
如何在C#中載入自己編寫的動態連結程式庫
相關文章:Creating a P/Invoke Library