C# DLLImport的理解

--------------------------------------------------------------------------------------------

先不考慮概念,簡單的說就是調用dll中的某個方法。以例子說明。

創建一個form,在其上添加按鈕。按鈕的點擊事件爲button1_Click(object sender, EventArgs e)。

    //struct 收集系統情況

    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEM_INFO
    {
        public uint dwOemId;
        public uint dwPageSize;
        public uint lpMinimumApplicationAddress;
        public uint lpMaximumApplicationAddress;
        public uint dwActiveProcessorMask;
        public uint dwNumberOfProcessors;
        public uint dwProcessorType;
        public uint dwAllocationGranularity;
        public uint dwProcessorLevel;
        public uint dwProcessorRevision;
    }

public partial class Form1 : Form

{

        public Form1()
        {
            InitializeComponent();
        }

        //獲取系統信息
        [DllImport("kernel32")]
        static extern void GetSystemInfo(ref SYSTEM_INFO pSI);

        private void button1_Click(object sender, EventArgs e)
        {
            SYSTEM_INFO pSI = new SYSTEM_INFO();
            GetSystemInfo(ref pSI);
        }

}

說明:

1.點擊按鈕的時候會發現pSI的值已經發生了變化,裏面包含系統信息。

2.SYSTEM_INFO爲自定義的結構體,但結構體的參數個數和參數類型要與GetSystemInfo()方法的一致。

3.DllImport的方法的必須寫成static extern ,可以修飾爲public等。

-------------------------------------------------------------------------------------------
        根據上面的調用方式,我們可以同樣方式調用自定義的dll嗎?
        首先創建一個工程Import,並有Class1
        namespace Import
        {
            public class Class1
            {
                public static string ImportMeth(string str)
                {
                    return "you are success!";
                }
            }
        }
        然後以同樣方式調用,
        //自定義的dll
        [DllImport("Import")]
        public static extern string ImportMeth(string a);
        在button1_Click(object sender, EventArgs e)裏追加以下代碼:
        string strRet = ImportMeth("123");
        運行後發現報錯"Unable to find an entry point named 'ImportMeth' in DLL 'Import'.":"",
        試着把dll引入到工程的參照中,一樣報錯。
        最終查出來,原來DLLImport 用於託管程序調符合DLL規範的非託管程序動態類庫.如果是調用託管程序類庫,直接引用就行了。
        所以我們不需要也不能DLLImport,而應該添加using Import;
        string strRet = Class1.ImportMeth("123");
        這樣就可以得到結果“you are success!”了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章