Unity - How to add C++ file directly to be used as a Plug-in

58 views Asked by At

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: https://docs.unity3d.com/2023.1/Documentation/Manual/PluginInspector.html

I followed these instructions here to use a .cpp file in Unity: https://docs.unity3d.com/2021.2/Documentation/Manual/WindowsPlayerCPlusPlusSourceCodePluginsForIL2CPP.html

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:

  1. Assets folder
  2. Assets/Plugins/x64 folder
  3. 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:(unknown assembly) type:(unknown type) member:(null)

What am I doing incorrectly?

1

There are 1 answers

0
ABS On

So I was trying this in Editor but I found that the Editor is Mono only and it can't support directly adding C++ files to it: https://forum.unity.com/threads/including-c-c-source-files-as-plugins-in-il2cpp-back-end.786287/