程式C++ to C#互動

來源:互聯網
上載者:User

標籤:tool   函數   bottom   rda   clr   width   程式   define   using   

第一次用C#調用C/C++產生的DLL檔案,感覺有點新鮮,事實上僅僅是實現了執行在公用語言執行庫 (CLR) 的控制之外的“Unmanaged 程式碼”(執行在公用語言執行庫(CLR)的控制之中的代碼碼稱為“Managed 程式碼“)的東西,如何運用在託管下的非託管呢?如今給感興趣的剛開始學習的人簡單地寫一個實現的全過程吧(有什麼問題千萬別笑):

1.用VS2008選擇其他語言(C++)建立一個控制台應用程式命名為Mydll1,然後選擇應用程式類型為DLL,確定

 項目

 

在標頭檔 stdafx.h 下加入例如以下聲明:

 

#define LIBEXPORT_API extern "C" __declspec(dllexport) 
LIBEXPORT_API int Add(int a, int b);

 

 

在MyDll.cpp中實現這個函數:



#include "stdafx.h"

int Add(int a,int b)
{
 return a+b;
}

 

注意假設實現的方法是聲明在其他標頭檔裡的,一定要 加#include "xxx.h" 來引用這個聲明了這個函數標頭檔。

產生MyDll.dll和MyDll.lib。

2.在Visual C# .net中引用dll檔案

建立Visual C#控制台應用程式命名為TestImportDll;

將MyDll.dll和MyDll.lib複製到可運行檔案檔案夾下():

在Praogram.cs中加入引用using System.Runtime.InteropServices;

按例如以下方式聲明一個將要引用MyDll.dll中函數的類:

  

 class test
    {
        //[DllImport("..\\..\\lib\\CppDemo.dll")]
        //public static extern void Function();

        //[DllImport("..\\..\\lib\\CppDemo.dll")]
        //public static extern int Add(int i, int j);
        [DllImport("..\\..\\Lib\\Mydll1.dll")]
        public static extern int Add(int a, int b);
    }

 

 最後在Main函數中調用這個類輸出結果:

 

 static void Main(string[] args)
        {           

            Console.WriteLine("result: " + test.Add(2, 3).ToString());

            Console.ReadLine();
        }以下是Program.cs的代碼:END():

程式C++ to C#互動

聯繫我們

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