在C#中調用VC編寫的dll庫 – -

來源:互聯網
上載者:User

如何在C#中使用C/C++寫的DLL。舉例說明:
建立VC工程DllDemo,建立的時候選擇MFC AppWizard(dll),選擇Regular Dll using shared MFC Dll或者MFC Extension Dll。
現在可以寫一個函數代碼,在DllDemo.cpp檔案中添加這些代碼。也可以使用新的檔案添加代碼;
extern “C“ __declspec(dllexport) int Add(int a,int b)
{
     AFX_MANAGE_STATE(AfxGetStaticModuleState());
     TRACE("Entering DllAdd\n");

     return a+b;
}

編譯工程。

下面建立一個C#的WinForm程式測試DllDemo:
啟動vs.net IDE,建立新的C#工程,選擇WinForm應用程式。
在Form1.cs中添加引用:using System.Runtime.InteropServices;
在pulic class Form1聲明的開頭添加代碼:
[DllImport("MotorControlDll.dll",EntryPoint="Add",ExactSpelling=false,CallingConvention=CallingConvention.Cdecl)]
public static extern int Add(int a,int b);

至於DllImport屬性的用法可以察看MSDN,對於各項參數有詳細的說明。

最後還要記得將DllDemo產生的位於Debug檔案中DllDemo.dll檔案加入到C#的WinForm程式的bin目錄下。
這樣就可以直接使用Add(int a,int b)函數。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.