C#調用C++動態庫(dll)


1.先創建一個C++空的動態庫

  

2.修改2個屬性

  (1)設置公共語言運行時支持,目的是將C++代碼編譯成為中間語言(clr),

    

  (2)

    

3. main.h中:

  #pragma once
  #include <string>

  //在被導出的函數前面一定要添加額extern “C來指明導出函數的時候使用C語言方式編譯和鏈接的,這樣保證函數定義的名字相同,否則如果默認按C++方式導出,那個函數名字就會         //變得亂七八糟,我們的程序就無法找到入口點了

       //__declspec(dllexport)”意思是將后面修飾的內容定義為DLL中要導出的內容

  _EXTERN_C     __declspec(dllexport) int FuncAdd(int a, int b);                            

  };

4.main.cpp中:

  #include "main.h"

  __declspec(dllexport)  int  FuncAdd(int a, int b)
  {
    return a + b;
  }

5. 創建C#工程,去調用dll

  public class Program
  {
    [DllImport(@"ConsoleApplication1.dll", EntryPoint = "FuncAdd", CallingConvention = CallingConvention.Cdecl)]
    public extern static int FuncAdd(int a,int b);
    static void Main()
    {
      int temp = FuncAdd(1, 2);
      Console.WriteLine(temp);

    }

       }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM