文章申明:本文來自JacksonDunstan的博客系列文章內容摘取和翻譯,版權歸其全部,附上原文的連接,你們能夠有空閱讀原文:C++ Scripting( in Unity)c++
上一篇文章寫完,有同窗以爲有點晦澀,其實能夠多認真看兩遍源碼,仔細琢磨一下,就會有一種茅塞頓開的感受:D。今天繼續上文,深刻討論一下C++做爲遊戲腳本的研究,本文會較長,須要寫一些示例代碼作講解。git
1、對C#指針(引用)的封裝github
在上文,咱們提到,C++對C#的調用,是基於C#的函數指針(引用)而來的,好比在C++中:json
//return transform handle || function pointer name || take a handle to the go
int32_t (*GameObjectGetTransform) (int32_t thiz);
爲了拓展性,咱們都會傾向於對於這種int32_t類型的數據作一個封裝,天然容易想到用一個結構體(結構體默認爲public)c#
namespace System { struct Object { int32_t Handle; } }
利用繼承的特色,咱們能夠延伸出其餘類型的結構體定義:app
namespace UnityEngine { struct Vector3 {float x; float y; float z;}; struct Transform:System::Object { void SetPosition(Vector3 val) { TransformSetPosition(Handle, val); } } struct GameObject:System::Object { GameObject() { Handle = GameObjectNew(); } Transform GetPosition() { Transform transform; transform.Handle = GameObjectGetTransform(Handle); return transform; } } }
2、對內存管理的控制ide
在C#部分,對於託管部分,是基於垃圾自動回收機制的,對於C++部分,相對較爲簡單的回收,能夠基於計數的回收機制,當對象的引用計數爲零的時候執行垃圾回收,那麼對於咱們能夠定義兩個全局變量來作相關的計數統計:函數
//global
int32_t managedObjectsRefCountLen; int32_t *managedObjectsRefCounts; //..... //init
managedObjectsRefCountLen = maxManagedObjects;//c#會傳入該數據
managedObjectsRefCounts = (int32_t*)calloc(maxManagedObjects, sizeof(int32_t));
這樣在GameObject的初始化和解析的時候能夠執行相關的內存管理操做:this
GameObject() { Handle = GameObjectNew(); managedObjectsRefCounts[Handle]++; } ~GameObject() { if(--managedObjectsRefCounts[Handle] == 0) { ReleaseObject(Handle); } }
對於其餘的結構體,能夠利用宏定義來實現相似的結構體定義中的操做。綜上,能夠實如今傳遞的時候對int32_t類型數據的封裝,其次能夠內嵌內存操做。總體代碼對於c#的修改很少,對於C++的修改較多。lua
3、代碼部分
對於c#部分的代碼,基本不修改,只是修改一下Init函數,添加內存管理相關的數據和函數,具體代碼以下:
.... //初始化函數及相關委託的修改
public delegate void InitDelegate(int maxManagedObjects, IntPtr releaseObject, IntPtr gameObjectNew, IntPtr gameObjectGetTransform, IntPtr transformSetPosition); .... ... #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX ... #elif UNITY_EDITOR_WIN ... #else [DllImport("NativeScript")] static extern void Init(int maxManagedObjects, IntPtr releaseObject, IntPtr gameObjectNew, IntPtr gameObjectGetTransform, IntPtr transformSetPosition); ... #endif
//新增釋放
delegate void ReleaseObjectDelegate(int handle); ... //修改Awake函數中對於初始化的操做
void Awake() { ... //init c++ libraray
const int maxManagedObjects = 1024; ObjectStore.Init(maxManagedObjects); Init(maxManagedObjects, Marshal.GetFunctionPointerForDelegate(new ReleaseObjectDelegate(ReleaseObject)), Marshal.GetFunctionPointerForDelegate(new GameObjectNewDelegate(GameObjectNew)), Marshal.GetFunctionPointerForDelegate(new GameObjectGetTransformDelegate(GameObjectGetTransform)), Marshal.GetFunctionPointerForDelegate(new TransformSetPositionDelegate(TransformSetPosition))); } ... //c# function for c++ to call
static void ReleaseObject(int handle) { ObjectStore.Remove(handle); } ...
C++部分的代碼修改較多,我就copy一下做者的工程源碼吧 :D
// For assert()
#include <assert.h>
// For int32_t, etc.
#include <stdint.h>
// For malloc(), etc.
#include <stdlib.h>
// For std::forward
#include <utility>
// Macro to put before functions that need to be exposed to C#
#ifdef _WIN32 #define DLLEXPORT extern "C" __declspec(dllexport)
#else
#define DLLEXPORT extern "C"
#endif
////////////////////////////////////////////////////////////////
// C# struct types
////////////////////////////////////////////////////////////////
namespace UnityEngine { struct Vector3 { float x; float y; float z; Vector3() : x(0.0f) , y(0.0f) , z(0.0f) { } Vector3( float x, float y, float z) : x(x) , y(y) , z(z) { } }; } ////////////////////////////////////////////////////////////////
// C# functions for C++ to call
////////////////////////////////////////////////////////////////
namespace Plugin { using namespace UnityEngine; void (*ReleaseObject)( int32_t handle); int32_t (*GameObjectNew)(); int32_t (*GameObjectGetTransform)( int32_t thiz); void (*TransformSetPosition)( int32_t thiz, Vector3 val); } ////////////////////////////////////////////////////////////////
// Reference counting of managed objects
////////////////////////////////////////////////////////////////
namespace Plugin { int32_t managedObjectsRefCountLen; int32_t* managedObjectRefCounts; void ReferenceManagedObject(int32_t handle) { assert(handle >= 0 && handle < managedObjectsRefCountLen); if (handle != 0) { managedObjectRefCounts[handle]++; } } void DereferenceManagedObject(int32_t handle) { assert(handle >= 0 && handle < managedObjectsRefCountLen); if (handle != 0) { int32_t numRemain = --managedObjectRefCounts[handle]; if (numRemain == 0) { ReleaseObject(handle); } } } } ////////////////////////////////////////////////////////////////
// Mirrors of C# types. These wrap the C# functions to present // a similiar API as in C#.
////////////////////////////////////////////////////////////////
namespace System { struct Object { int32_t Handle; Object(int32_t handle) { Handle = handle; Plugin::ReferenceManagedObject(handle); } Object(const Object& other) { Handle = other.Handle; Plugin::ReferenceManagedObject(Handle); } Object(Object&& other) { Handle = other.Handle; other.Handle = 0; } }; //宏定義操做
#define SYSTEM_OBJECT_LIFECYCLE(ClassName, BaseClassName) \ ClassName(int32_t handle) \ : BaseClassName(handle) \ { \ } \ \ ClassName(const ClassName& other) \ : BaseClassName(other) \ { \ } \ \ ClassName(ClassName&& other) \ : BaseClassName(std::forward<ClassName>(other)) \ { \ } \ \ ~ClassName() \ { \ DereferenceManagedObject(Handle); \ } \ \ ClassName& operator=(const ClassName& other) \ { \ DereferenceManagedObject(Handle); \ Handle = other.Handle; \ ReferenceManagedObject(Handle); \ return *this; \ } \ \ ClassName& operator=(ClassName&& other) \ { \ DereferenceManagedObject(Handle); \ Handle = other.Handle; \ other.Handle = 0; \ return *this; \ } } namespace UnityEngine { using namespace System; using namespace Plugin; struct GameObject; struct Component; struct Transform; struct GameObject : Object { SYSTEM_OBJECT_LIFECYCLE(GameObject, Object) GameObject(); Transform GetTransform(); }; struct Component : Object { SYSTEM_OBJECT_LIFECYCLE(Component, Object) }; struct Transform : Component { SYSTEM_OBJECT_LIFECYCLE(Transform, Component) void SetPosition(Vector3 val); }; GameObject::GameObject() : GameObject(GameObjectNew()) { } Transform GameObject::GetTransform() { return Transform(GameObjectGetTransform(Handle)); } void Transform::SetPosition(Vector3 val) { TransformSetPosition(Handle, val); } } ////////////////////////////////////////////////////////////////
// C++ functions for C# to call
////////////////////////////////////////////////////////////////
// Init the plugin
DLLEXPORT void Init( int32_t maxManagedObjects, void (*releaseObject)(int32_t), int32_t (*gameObjectNew)(), int32_t (*gameObjectGetTransform)(int32_t), void (*transformSetPosition)(int32_t, UnityEngine::Vector3)) { using namespace Plugin; // Init managed object ref counting
managedObjectsRefCountLen = maxManagedObjects; managedObjectRefCounts = (int32_t*)calloc( maxManagedObjects, sizeof(int32_t)); // Init pointers to C# functions
ReleaseObject = releaseObject; GameObjectNew = gameObjectNew; GameObjectGetTransform = gameObjectGetTransform; TransformSetPosition = transformSetPosition; } // Called by MonoBehaviour.Update
DLLEXPORT void MonoBehaviourUpdate() { using namespace UnityEngine; static int32_t numCreated = 0; if (numCreated < 10) { GameObject go; Transform transform = go.GetTransform(); float comp = (float)numCreated; Vector3 position(comp, comp, comp); transform.SetPosition(position); numCreated++; } }
4、c#和Unity API 的導出
寫到上面部分,基本對於c#和c++之間的操做有一個總體的較爲完整的講解,還有一個沒有提起,那就是,怎麼將 unity 的API導出給C++使用呢?做者給出了一個導出方式:JSON導出這讓熟悉c#導出到lua的同窗能夠發現殊途同歸之妙,其基本的導出設計爲:
{
"Assemblies": [
{
"Path": "/Applications/Unity/Unity.app/Contents/Managed/UnityEngine.dll",
"Types": [
{
"Name": "UnityEngine.Object",
"Constructors": [],
"Methods": [],
"Properties": [],
"Fields": []
},
{
"Name": "UnityEngine.GameObject",
"Constructors": [
{
"Types": []
}
],
"Properties": [ "transform" ],
"Fields": []
},
{
"Name": "UnityEngine.Component",
"Constructors": [],
"Methods": [],
"Properties": [],
"Fields": []
},
{
"Name": "UnityEngine.Transform",
"Constructors": [],
"Methods": [],
"Properties": [ "position" ],
"Fields": []
}
]
}
]
}
總體設計簡介易懂,固然,並非全部的c#特性均可以被導出,json的導出不支持:Array/out and ref/ delegate/ generic functions and types/ struct types,不知後期做者是否考慮擴展對這些不兼容的特效的導出。
使用json導出,總體的修改和使用很是簡單,好比對Component,須要添加對其transform特性的導出,那麼只須要修改成:
"Properties":["transform"]
那麼,保存後從新導出,就能夠獲得transform特性。
此外,對於.Net的一些API, 也可使用JSON導出的方式:
{
"Path": "/Applications/Unity/Unity.app/Contents/Mono/lib/mono/unity/System.dll",
"Types": [
{
"Name": "System.Diagnostics.Stopwatch",
"Constructors": [
{
"Types": []
}
],
"Methods": [
{
"Name": "Start",
"Types": []
},
{
"Name": "Reset",
"Types": []
}
],
"Properties": [ "ElapsedMilliseconds" ],
"Fields": []
}
]
}
基於上面的各個部分,總體的遊戲工程,能夠分爲2個部分:邏輯代碼部分和binding相關的部分,做者給出的工程規劃:
Assets
|- Game.cpp // Game-specific code. Can rename this file, add headers, etc.
|- NativeScriptTypes.json // JSON describing which .NET types the game wants to expose to C++
|- NativeScriptConstants.cs // Game-specific constants such as plugin names and paths
|- NativeScript/ // C++ scripting system. Drop this into your project.
|- Editor/
|- GenerateBindings.cs // Code generator
|- Bindings.cs // C# code to expose functionality to C++
|- ObjectStore.cs // Object handles system
|- Bindings.h // C++ wrapper types for C# (declaration)
|- Bindings.cpp // C++ wrapper types for C# (definition)
|- BootScript.cs // MonoBehaviour to boot up the C++ plugin
|- BootScene.unity // Scene with just BootScript on an empty GameObject
對於NativeScript來講,至關於基本的binding相關的東西,對於任何工程都適用,對於其餘部分,則根據具體的工程來設計。基於這樣的設計,須要作到三個基本規範:
一、須要定義一個全局的類:
public static class NativeScriptConstants { /// <summary>
/// Name of the plugin used by [DllImport] when running outside the editor /// </summary>
public const string PluginName = "NativeScript"; /// <summary>
/// Path to load the plugin from when running inside the editor /// </summary>
#if UNITY_EDITOR_OSX
public const string PluginPath = "/NativeScript.bundle/Contents/MacOS/NativeScript"; #elif UNITY_EDITOR_LINUX
public const string PluginPath = "/NativeScript.so"; #elif UNITY_EDITOR_WIN
public const string PluginPath = "/NativeScript.dll"; #endif
/// <summary>
/// Maximum number of simultaneous managed objects that the C++ plugin uses /// </summary>
public const int MaxManagedObjects = 1024; /// <summary>
/// Path within the Unity project to the exposed types JSON file /// </summary>
public const string ExposedTypesJsonPath = "NativeScriptTypes.json"; }
二、NativeScriptConstants.ExposedTypesJsonPath須要指向前面所提到的json導出文件;
三、在C++代碼部分,須要定義2個函數用來執行相關的更新
// Called when the plugin is initialized
void PluginMain()
{
}
// Called for MonoBehaviour.Update
void PluginUpdate()
{
}
最後,總體的工程能夠在github上找到,給出工程的連接:
jacksondunstan/UnityNativeScripting
Over!