C#調用c++的動態庫dll示範常式

來源:互聯網
上載者:User

標籤:

1.首先編寫c++動態庫

extern "C" __declspec(dllexport)int __stdcall add(int x, int y){return x + y;}


extern "C" __declspec(dllexport)

extern "C"使得在C++中使用C編譯方式成為可能。在“C++”下定義“C”函數,需要加extern “C”關鍵詞。用extern "C"來指明該函數使用C編譯方式。輸出的“C”函數可以從“C”代碼裡調用.
使用微軟專用的_declspec (dllexport)  
cpp檔案在編譯為OBJ檔案時要對函數進行重新命名,C語言會把函數name重新命名為_name,而C++會重新命名為[email protected]@decoration,
extern "C"表示用C語言的格式將函數重新命名
要輸出整個的類,對類使用_declspec(_dllexpot);要輸出類的成員函數,則對該函數使用_declspec(_dllexport)


__stdcall 限定修飾符需要添加。不加這個限定符,不能成功調用,不知道為什嗎??


2.c#調用c++dll庫中封裝的介面函數

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Runtime.InteropServices;//public class DLL{    [DllImport("DLLCpp.dll", EntryPoint = "add")]    public extern static int add(int x, int y);//與dll中一致 }namespace DLLTest{    class Program    {        static void Main(string[] args)        {            int ret = DLL.add(2, 3);            Console.WriteLine(ret);            Console.ReadKey();                   }    }}

using System.Runtime.InteropServices;

一般用到其中的DllImport,它用來調用windows中一些DLL的函數(Windows API),或調用自己用c++寫的DLL中的函數

public class DLL
{
    [DllImport("DLLCpp.dll", EntryPoint = "add")]


    public extern static int add(int x, int y);//與dll中一致 
}

注意:c#如果是64位的環境,c++封裝動態庫的時候,設定為x64。 32位為什麼不能調用,還不清楚?

C#調用c++的動態庫dll示範常式

聯繫我們

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