Unity3d 調用C++寫的DLL

  • 一、建立DLL
    • 打開VS2010,建立一個win32應用程序,選擇建立一個DLL類型的空項目。
    • 新建一個頭文件和一個源文件。
    • 在頭文件中寫入
       
      1. #if defined (EXPORTBUILD)    
      2. # define _DLLExport __declspec (dllexport)    
      3. # else    
      4. # define _DLLExport __declspec (dllimport)    
      5. #endif    
      6.     
      7. extern "C"  int _DLLExport MyADD(int x,int y);    
    • 在源文件中定義方法的操做
       
      1. //宏定義    
      2. #define  EXPORTBUILD    
      3.     
      4. //加載頭文件    
      5. #include "DLL.h"    
      6.     
      7. //設置函數    
      8. int _DLLExport MyADD(int x,int y)    
      9. {    
      10.     return x+y;    
      11. }    
    • 傳入兩個參數會返回兩個參數的和,而後編譯這個項目,將生成的dll拷貝到Unity工程中的Asset/Plugins文件夾中

 

 

  • 二、調用DLL
    • 使用C#來調用DLL,首先建立一個C#腳本。添加using指令
       
      1. using System.Runtime.InteropServices;  
    • 使用[DllImport("Dll名字")]指明要引用的DLL,而後聲明要使用的DLL中的方法。
    •  
      1. using UnityEngine;  
      2. using System.Collections;  
      3. using System.Runtime.InteropServices;  
      4.   
      5. public class test : MonoBehaviour {  
      6.     [DllImport("test")]  
      7.     private static extern int MyADD(int x,int y);  
      8.     int i = MyADD(5,7);  
      9.       
      10.     void OnGUI()  
      11.     {  
      12.         GUI.Button(new Rect(1,1,200,100),i.ToString());  
      13.     }  
      14. }  
相關文章
相關標籤/搜索