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. }  
原文地址:https://www.cnblogs.com/leesymbol/p/6587544.html