How to use a C++ dll in Unity3D?

后端 未结 3 1031
我寻月下人不归
我寻月下人不归 2021-02-02 03:30

I am aware of this similar question, but it does not respond to my problem.

I have written two .dlls using Visual Studio 2010. One is in C++, and communicat

相关标签:
3条回答
  • 2021-02-02 04:05

    The problem is that the DLL is not being found when the p/invoke runtime code calls LoadLibrary(YourNativeDllName).

    You could resolve this by making sure that your DLL is on the DLL search path at the point where the first p/invoke call to it is made. For example by calling SetDllDirectory.

    The solution that I personally prefer is for your managed code to p/invoke a call to LoadLibrary passing the full absolute path to the native DLL. That way when the subsequent p/invoke induced call to LoadLibrary(YourNativeDllName) is make, your native DLL is already in the process and so will be used.

    internal static class NativeMethods
    {
        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
        internal static extern IntPtr LoadLibrary(
            string lpFileName
        );
    }
    

    And then somewhere in your code:

    private static IntPtr lib;
    
    ....
    
    public static void LoadNativeDll(string FileName)
    {
        if (lib != IntPtr.Zero)
        {
            return;
        }
    
        lib = NativeMethods.LoadLibrary(FileName);
        if (lib == IntPtr.Zero)
        {
            throw new Win32Exception();
        }
    }
    

    Just make sure that you call LoadNativeDll passing the full path to the native library, before you call any of the p/invokes to that native library.

    0 讨论(0)
  • 2021-02-02 04:09

    Note that the DllNotFoundException can be caused by building your Unity DLL in Debug instead of Release!

    A simple oversight that can cause a headache.

    0 讨论(0)
  • 2021-02-02 04:24

    This also happens when Unity can find your DLL, but is not able to find it's dependencies. Obvious fix is to place dependency DLLs into /Plugins as well, or link your dependencies statically.

    Less obvious reason is when your DLL depends on Visual Studio runtime library dynamically, i.e. is built with Properties -> C/C++ -> Code Generation -> /MD option. Change it to /MT to link with runtime statically.

    0 讨论(0)
提交回复
热议问题