EntryPointNotFoundException With Unity Plugin

Viewed 1801

I'm very new to writing c++ plugins for unity but must do so now. I have been loosely following this tutorial and created the following in a visual studio dll project uncreatively called UnityPluginTest:

#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);
    }
}

I created a completely new unity project to test it (Unity 2020.2.f1 if it matters), and copied the compiled .dll file into a new folder Assets/Plugins. I then made a new script called (equally uncreatively) TestFirstUnityPluginTest.cs which contains the following:

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));
    }
}

When I put the script on a gameobject and hit play, I get an error stating "EntryPointNotFoundException: RandomNumber" with a stack trace pointing to the Debug.Log() call. Any ideas what I might be doing wrong? Thank you in advance.

1 Answers

You should specify entry point and use DECORATED name:

replace [DllImport(dll)] by [DllImport("YOUR_DLL_NAME.dll", EntryPoint = "DecoratedFunctionName")]

My C++ code:

__declspec(dllexport) int Double(int number)
{
    return number * 2;
}

My Unity3d C# code:

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

Decorated name - name of the function inside DLL (compiler renames it). Dumpbin.exe helps to find it: VisualStudion2019 -> Tools -> CommandLine -> DeveloperComandPrompt

cd <your PathToDLL>
dumpbin /exports Dll4_CPP.dll

it will print:

...
1    0 00011217 ?Double@@YAHH@Z = @ILT+530(?Double@@YAHH@Z)
...

Source

Related