Unity3d 調用C++寫的DLL


  • 1、創建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文件夾中

 

 

  • 2、調用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. }  


免責聲明!

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



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