且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 C++ 代码添加到 Unity 项目中?

更新时间:2021-09-04 01:48:26

您需要将 C++ 代码包装在 C 函数中,然后通过 P/Invoke 使用它们.

You need to wrap the C++ code in C functions, then use them through P/Invoke.

例如

MyPlugin.cpp

#define MY_API extern "C"

class Context
{
public:
    const int version = 12345;
};

MY_API int GetVersion(const Context* _pContext)
{
    if (_pContext == nullptr)
    {
        return 0;
    }
    return _pContext->version;
}

MY_API Context* CreateContext()
{
    return new Context();
}

MY_API void DestroyContext(const Context* _pContext)
{
    if (_pContext != nullptr)
    {
        delete _pContext;
    }
}

然后将上面的代码编译成Windows的*.dll,Android的*.so,iOS的Cocoa Touch Static Library和捆绑适用于macOS.

Then compile the above code into *.dll for Windows, *.so for Android, Cocoa Touch Static Library for iOS and bundle for macOS.

在 C# 中的使用:

MyPlugin.cs

using System;
using System.Runtime.InteropServices;
using UnityEngine;

public class MyAPI : MonoBehaviour
{
#if UNITY_EDITOR || UNITY_STANDALONE
    const string dllname = "MyPlugin";
#elif UNITY_IOS
    const string dllname = "__Internal";
#endif

    [DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
    private static extern IntPtr CreateContext();

    [DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
    private static extern int GetVersion(IntPtr _pContext);

    [DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
    private static extern void DestroyContext(IntPtr _pContext);

    static MyAPI()
    {
        Debug.Log("Plugin name: " + dllname);
    }

    void Start ()
    {
        var context = CreateContext();
        var version = GetVersion(context);
        Debug.LogFormat("Version: {0}", version);
        DestroyContext(context);
    }
}

参考文献:

  1. https://docs.unity3d.com/Manual/NativePlugins.html
  2. http://www.mono-project.com/docs/advanced/pinvoke/