您需要将C代码包装在C函数中,然后通过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;
}
}
然后将上面的代码编译为* .dll for Windows,* .so for Android,Cocoa Touch Static Library for iOS和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);
}
}
参考文献: