DllNotFoundException in unity3d plugin for c++ dll

后端 未结 7 1498
死守一世寂寞
死守一世寂寞 2021-01-11 17:49

I am working on the Unity Plugin project and try to import the c++ native dll from c# file. But I keep getting dllnotfoundexception.

c++ dll code:

7条回答
  •  别那么骄傲
    2021-01-11 18:36

    Thanks to this Unity forum post I came up with a nice solution which modifies the PATH-environment variable at runtime:

    • Put all DLLs (both the DLLs which Unity interfaces with and their dependent DLLs) in Project\Assets\Wherever\Works\Best\Plugins.
    • Put the following static constructor into a class which uses the plugin:

      static MyClassWhichUsesPlugin() // static Constructor
      {
          var currentPath = Environment.GetEnvironmentVariable("PATH",
              EnvironmentVariableTarget.Process);
      #if UNITY_EDITOR_32
          var dllPath = Application.dataPath
              + Path.DirectorySeparatorChar + "SomePath"
              + Path.DirectorySeparatorChar + "Plugins"
              + Path.DirectorySeparatorChar + "x86";
      #elif UNITY_EDITOR_64
          var dllPath = Application.dataPath
              + Path.DirectorySeparatorChar + "SomePath"
              + Path.DirectorySeparatorChar + "Plugins"
              + Path.DirectorySeparatorChar + "x86_64";
      #else // Player
          var dllPath = Application.dataPath
              + Path.DirectorySeparatorChar + "Plugins";
      
      #endif
          if (currentPath != null && currentPath.Contains(dllPath) == false)
              Environment.SetEnvironmentVariable("PATH", currentPath + Path.PathSeparator
                  + dllPath, EnvironmentVariableTarget.Process);
      }
      
    • Add [InitializeOnLoad] to the class to make sure that the constructor is run at editor launch:

       [InitializeOnLoad]
       public class MyClassWhichUsesPlugin
       {
           ...
           static MyClassWhichUsesPlugin() // static Constructor
           {
               ...
           }
        }
      

    With this script there is no need to copy around DLLs. The Unity editor finds them in the Assets/.../Plugins/...-folder and the executable finds them in ..._Data/Plugins-directory (where they get automatically copied when building).

提交回复
热议问题