c++託管使用c#動態庫

來源:互聯網
上載者:User

     拿來一個dll,是c#編譯的,我在c++程式中需要使用該dll,網上查了相關資料,需要用到 c++託管相關知識,即CLR公用語言時運行環境。具體使用步驟如下:

          1.拷貝dll到工程運行目錄下。
    2.引用:
           #using \"..\\debug\\CTest.dll\"
         using namespace CTest;  
         如果 程式中引用了 其他.net組建的程式集,根據提示進行引用。例如缺少:程式集“System.Windows.Forms 則添加 #using <System.Windows.Forms.dll>
     3.項目屬性,修改“Common Language Runtime 支援”為 "/clr".
  4.託管對象使用:
              ClassName ^p = gcnew ClassName();
                p->Fun();  // 調用dll的函數

         //delete p;
               通過gcnew來執行個體化,無需使用delete來釋放記憶體,gcnew出來的記憶體由
         虛擬機器託管,程式結束後,會自動銷毀。

           5.如果dll提供的介面,需要註冊回調。則文法和c#註冊回調文法一樣

  如:

       c#裡回呼函數定義如下 :
  namespace CTest
  {
  public class ClassName : UserControl
  {
    public ClassName();
    public event ClassName.DataReceive myDataReceive;
    public delegate void DataReceive(int iDoor, string sOPtag);
  }
       }

        則回調設定方法:       

p->myDataReceive += gcnew ClassName::DataReceive(GetAccessMsg); 

    GetAccessMsg 定義如下:

 void GetAccessMsg(int iDoor, System::String^ sOPtag)) {     // 把 System::String^ 類型轉換成 char*     IntPtr sptr = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(sOPtag);     char* pMsg = (char*)sptr.ToPointer(); cout<<iDoor<<endl; }}

                    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.