How to add C++ file directly in Unity as a plugin

I am using Unity 2023.3. I wanted to use C++ code directly as plugin in Unity. In their documentation here it mentions that it detects .cpp as a plugin: Unity - Manual: Import and configure plug-ins

I followed these instructions here to use a .cpp file in Unity: Unity - Manual: Windows Player: C++ source code plugins for IL2CPP

I am on a Windows PC.

My Test.cpp file is:

extern "C" __declspec(dllexport) int __stdcall CountLettersInString(wchar_t* str)
{
    int length = 0;
    while (*str++ != L'\0')
        length++;
    return length;
}

And the C# script that I created in Unity is:

using System.Runtime.InteropServices;
using UnityEngine;

public class CPPTest : MonoBehaviour
{
    [DllImport("__Internal")]
    private static extern int
    CountLettersInString([MarshalAs(UnmanagedType.LPWStr)]string str);

    public void DoSomething()
    {
        int i = CountLettersInString("abc");
        Debug.Log(i);
    }

}

I call the DoSomething() from a button press.

I have set the Player Setting → Configuration → Scripting Backend to IL2CPP for Windows.

I have tried adding the .cpp file in the following locations:

  • Assets folder
  • Assets/Plugins/x64 folder
  • Assets/Editor folder

Every time I changed the location of the .cpp file, I closed down the editor, moved the file to the new location in Files Explorer and then re-opened the editor.

However, I always get this error: EntryPointNotFoundException: CountLettersInString assembly: type: member:

What am I doing incorrectly?

In case you’re testing this in-Editor:

4 Likes

Just in case you’re keep going to waste time like this: none of this is necessary. It is sufficient to copy a DLL somewhere to the project’s Assets branch and tab into Unity editor. Unity will recognize the changed files and import them, no matter the type of the file.

Typically you’ll set up a post-build step with a simple command like “xcopy /y source target” to make sure the DLL in the project is always up to date with the DLL built by its solution.