使用 Unity 插件的 EntryPointNotFoundException

Hom*_*ire 6 c++ dll runtime-error unity-game-engine

我对编写 Unity 的 C++ 插件非常陌生,但现在必须这样做。我一直在松散地遵循教程,并在一个名为 UnityPluginTest 的 Visual Studio DLL 项目中创建了以下内容:

#include <stdint.h>
#include <stdlib.h>
#include <time.h>

#define DLLExport __declspec (dllexport)

extern "C"
{
    DLLExport int RandomNumber(int min, int max)
    {
        srand((unsigned int)time(0));
        return (rand() % (max - min) + min);
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个全新的 Unity 项目来测试它(Unity 2020.2.f1,如果重要的话),并将编译后的 .dll 文件复制到新文件夹 Assets/Plugins 中。然后我创建了一个名为(同样没有创意的)TestFirstUnityPluginTest.cs 的新脚本,其中包含以下内容:

using System.Runtime.InteropServices;
using UnityEngine;

public class TestFirstUnityPluginTest : MonoBehaviour
{
    const string dll = "__Internal";

    [DllImport(dll)]
    private static extern int RandomNumber(int min, int max);

    void Start()
    {
        Debug.Log(RandomNumber(0, 10));
    }
}
Run Code Online (Sandbox Code Playgroud)

当我将脚本放在游戏对象上并点击播放时,我收到一条错误消息,指出“EntryPointNotFoundException:RandomNumber”,并且堆栈跟踪指向 Debug.Log() 调用。有什么想法我可能做错了什么吗?先感谢您。

And*_*wPt 1

您应该指定入口点并使用 DECORATED 名称:

将 [DllImport(dll)] 替换为 [DllImport("YOUR_DLL_NAME.dll", EntryPoint = "DecolatedFunctionName")]

我的C++代码:

__declspec(dllexport) int Double(int number)
{
    return number * 2;
}
Run Code Online (Sandbox Code Playgroud)

我的 Unity3d C# 代码:

[DllImport("Dll4_CPP.dll", EntryPoint = "?Double@@YAHH@Z")]
public static extern int Double(int number);
void Start()
{
    Debug.Log(Double(10));
}
Run Code Online (Sandbox Code Playgroud)

修饰名 - DLL 内函数的名称(编译器重命名)。 Dumpbin.exe有助于找到它:VisualStudion2019 -> Tools -> CommandLine -> DeveloperComandPrompt

cd <your PathToDLL>
dumpbin /exports Dll4_CPP.dll
Run Code Online (Sandbox Code Playgroud)

它将打印:

...
1    0 00011217 ?Double@@YAHH@Z = @ILT+530(?Double@@YAHH@Z)
...
Run Code Online (Sandbox Code Playgroud)

来源