Refactor #2746 to use ScriptingObjectInterfaceReference for C# too instead of attribute

Use `MarshalAs=ScriptingObject*` for more universal way of marshaling data between C++ and C#
This commit is contained in:
2026-09-14 06:58:40 +02:00
parent a7754f3137
commit 0fc3972cea
24 changed files with 527 additions and 792 deletions
@@ -1,14 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using System;
namespace FlaxEngine
{
/// <summary>
/// Marks a generated interface property as a native scripting object interface reference.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ScriptingObjectInterfaceReferenceAttribute : Attribute
{
}
}
@@ -1,14 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using System;
namespace FlaxEngine
{
/// <summary>
/// Marks a generated interface property as a native soft object interface reference.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class SoftObjectInterfaceReferenceAttribute : Attribute
{
}
}
+23 -88
View File
@@ -281,102 +281,22 @@ class ScriptingObjectReference;
template<typename T>
class ScriptingObjectInterfaceReference;
template<typename T>
class SoftObjectInterfaceReference;
template<typename T>
struct MConverter<ScriptingObjectReference<T>>
{
MObject* Box(const ScriptingObjectReference<T>& data, const MClass* klass)
{
return data.GetManagedInstance();
}
void Unbox(ScriptingObjectReference<T>& result, MObject* data)
{
result = (T*)ScriptingObject::ToNative(data);
}
void ToManagedArray(MArray* result, const Span<ScriptingObjectReference<T>>& data)
{
if (data.Length() == 0)
return;
MObject** objects = (MObject**)Allocator::Allocate(data.Length() * sizeof(MObject*));
for (int32 i = 0; i < data.Length(); i++)
objects[i] = data[i].GetManagedInstance();
MCore::GC::WriteArrayRef(result, Span<MObject*>(objects, data.Length()));
Allocator::Free(objects);
}
void ToNativeArray(Span<ScriptingObjectReference<T>>& result, const MArray* data)
{
MObject** dataPtr = MCore::Array::GetAddress<MObject*>(data);
for (int32 i = 0; i < result.Length(); i++)
result.Get()[i] = (T*)ScriptingObject::ToNative(dataPtr[i]);
}
};
template<typename TReference, typename TInterface>
struct MInterfaceReferenceConverter
{
MObject* Box(const TReference& data, const MClass* klass)
{
return data.GetManagedInstance();
}
void Unbox(TReference& result, MObject* data)
{
result = ScriptingObject::ToInterface<TInterface>(ScriptingObject::ToNative(data));
}
void ToManagedArray(MArray* result, const Span<TReference>& data)
{
if (data.Length() == 0)
return;
MObject** objects = (MObject**)Allocator::Allocate(data.Length() * sizeof(MObject*));
for (int32 i = 0; i < data.Length(); i++)
objects[i] = data[i].GetManagedInstance();
MCore::GC::WriteArrayRef(result, Span<MObject*>(objects, data.Length()));
Allocator::Free(objects);
}
void ToNativeArray(Span<TReference>& result, const MArray* data)
{
MObject** dataPtr = MCore::Array::GetAddress<MObject*>(data);
for (int32 i = 0; i < result.Length(); i++)
result.Get()[i] = ScriptingObject::ToInterface<TInterface>(ScriptingObject::ToNative(dataPtr[i]));
}
};
// Converter for Scripting Interface References.
template<typename T>
struct MConverter<ScriptingObjectInterfaceReference<T>> : MInterfaceReferenceConverter<ScriptingObjectInterfaceReference<T>, T>
{
};
// Converter for Soft Object Interface References.
template<typename T>
struct MConverter<SoftObjectInterfaceReference<T>> : MInterfaceReferenceConverter<SoftObjectInterfaceReference<T>, T>
{
};
// Converter for Asset References.
template<typename T>
class AssetReference;
template<typename T>
struct MConverter<AssetReference<T>>
template<typename Reference, typename Object>
struct MObjectReferenceConverter
{
MObject* Box(const AssetReference<T>& data, const MClass* klass)
MObject* Box(const Reference& data, const MClass* klass)
{
return data.GetManagedInstance();
}
void Unbox(AssetReference<T>& result, MObject* data)
void Unbox(Reference& result, MObject* data)
{
result = (T*)ScriptingObject::ToNative(data);
result = (Object*)ScriptingObject::ToNative(data);
}
void ToManagedArray(MArray* result, const Span<AssetReference<T>>& data)
void ToManagedArray(MArray* result, const Span<Reference>& data)
{
if (data.Length() == 0)
return;
@@ -387,14 +307,29 @@ struct MConverter<AssetReference<T>>
Allocator::Free(objects);
}
void ToNativeArray(Span<AssetReference<T>>& result, const MArray* data)
void ToNativeArray(Span<Reference>& result, const MArray* data)
{
MObject** dataPtr = MCore::Array::GetAddress<MObject*>(data);
for (int32 i = 0; i < result.Length(); i++)
result.Get()[i] = (T*)ScriptingObject::ToNative(dataPtr[i]);
result.Get()[i] = (Object*)ScriptingObject::ToNative(dataPtr[i]);
}
};
template<typename T>
struct MConverter<ScriptingObjectReference<T>> : MObjectReferenceConverter<ScriptingObjectReference<T>, T>
{
};
template<typename T>
struct MConverter<ScriptingObjectInterfaceReference<T>> : MObjectReferenceConverter<ScriptingObjectInterfaceReference<T>, ScriptingObject>
{
};
template<typename T>
struct MConverter<AssetReference<T>> : MObjectReferenceConverter<AssetReference<T>, T>
{
};
// TODO: use MarshalAs=Guid on SoftAssetReference to pass guid over bindings and not load asset in glue code
template<typename T>
class SoftAssetReference;
@@ -0,0 +1,188 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using System;
#if FLAX_EDITOR
using System.Globalization;
using System.ComponentModel;
#endif
namespace FlaxEngine
{
/// <summary>
/// The scripting object reference with interface.
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
#if FLAX_EDITOR
[CustomEditor(typeof(FlaxEditor.CustomEditors.Editors.ScriptingObjectInterfaceReferenceEditor))]
[TypeConverter(typeof(TypeConverters.ScriptingObjectInterfaceReferenceConverter))]
#endif
public struct ScriptingObjectInterfaceReference<T> : IComparable, IComparable<ScriptingObjectInterfaceReference<T>> where T : class
{
private Object _object;
/// <summary>
/// Gets or sets the referenced object that implements the interface.
/// </summary>
public Object Object
{
get => _object;
set => _object = value != null && value is T ? value : null;
}
/// <summary>
/// Gets or sets the referenced object that implements the interface.
/// </summary>
[NoSerialize]
public T Interface
{
get => _object as T;
set
{
var obj = value as Object;
if (value == null || obj != null)
_object = obj;
else
throw new InvalidCastException($"Cannot use object of type {value.GetType().FullName} for ScriptingObjectInterfaceReference<{typeof(T).FullName}>. It needs to inherit from {typeof(Object).FullName}.");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptingObjectInterfaceReference{T}"/> structure.
/// </summary>
/// <param name="obj">The object to link.</param>
public ScriptingObjectInterfaceReference(Object obj)
{
Object = obj;
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptingObjectInterfaceReference{T}"/> structure.
/// </summary>
/// <param name="interfaceObj">The interface object to link.</param>
public ScriptingObjectInterfaceReference(T interfaceObj)
{
Interface = interfaceObj;
}
/// <summary>
/// Implicit cast operator to typed interface.
/// </summary>
/// <param name="value">Reference</param>
/// <returns>Interface</returns>
public static explicit operator T(ScriptingObjectInterfaceReference<T> value)
{
return value._object as T;
}
/// <summary>
/// Implicit cast operator from object to reference.
/// </summary>
/// <param name="obj">The object to link.</param>
/// <returns>Reference</returns>
public static explicit operator ScriptingObjectInterfaceReference<T>(T obj)
{
return new ScriptingObjectInterfaceReference<T>(obj);
}
/// <summary>
/// Implicit cast operator to object.
/// </summary>
/// <param name="value">Reference</param>
/// <returns>Object</returns>
public static implicit operator Object(ScriptingObjectInterfaceReference<T> value)
{
return value._object;
}
/// <summary>
/// Implicit cast operator from object to reference.
/// </summary>
/// <param name="obj">Object</param>
/// <returns>Reference</returns>
public static implicit operator ScriptingObjectInterfaceReference<T>(Object obj)
{
return new ScriptingObjectInterfaceReference<T>(obj);
}
/// <inheritdoc />
public override string ToString()
{
return _object?.ToString() ?? "<null>";
}
/// <inheritdoc />
public override int GetHashCode()
{
return Object.GetUnmanagedPtr(_object).GetHashCode();
}
/// <inheritdoc />
public int CompareTo(object obj)
{
if (obj is ScriptingObjectInterfaceReference<T> other)
return CompareTo(other);
return 0;
}
/// <inheritdoc />
public int CompareTo(ScriptingObjectInterfaceReference<T> other)
{
return Object.GetUnmanagedPtr(_object).CompareTo(Object.GetUnmanagedPtr(other._object));
}
}
}
#if FLAX_EDITOR
namespace FlaxEngine.TypeConverters
{
internal class ScriptingObjectInterfaceReferenceConverter : TypeConverter
{
/// <inheritdoc />
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
/// <inheritdoc />
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return false;
return base.CanConvertTo(context, destinationType);
}
/// <inheritdoc />
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string str && context is DummyTypeDescriptorContext internalContext)
{
var type = internalContext.CurrentType;
Json.JsonSerializer.ParseID(str, out var id);
var obj = Object.Find(ref id, type.GetGenericArguments()[0]);
var objectField = type.GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
value = Activator.CreateInstance(type);
objectField.SetValue(value, obj);
return value;
}
return base.ConvertFrom(context, culture, value);
}
/// <inheritdoc />
public override unsafe object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var objectField = value.GetType().GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
var obj = objectField.GetValue(value) as Object;
if (obj == null)
return string.Empty;
var id = obj.ID;
return Json.JsonSerializer.GetStringID(&id);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
#endif
@@ -2,17 +2,15 @@
#pragma once
#include "Engine/Scripting/ScriptingObjectInterfaceReferenceUtils.h"
#include "ScriptingObjectReference.h"
/// <summary>
/// The scene object interface reference.
/// The scripting object reference with interface.
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
template<typename T>
API_CLASS(InBuild) class ScriptingObjectInterfaceReference : public ScriptingObjectReferenceBase
API_CLASS(Template, MarshalAs=ScriptingObject*) class ScriptingObjectInterfaceReference : public ScriptingObjectReferenceBase
{
typedef ScriptingObjectInterfaceReferenceHelper<T> Helper;
public:
typedef ScriptingObjectInterfaceReference<T> Type;
@@ -28,8 +26,8 @@ public:
/// Initializes a new instance of the <see cref="ScriptingObjectInterfaceReference"/> class.
/// </summary>
/// <param name="obj">The object to link.</param>
ScriptingObjectInterfaceReference(SceneObject* obj)
: ScriptingObjectReferenceBase(Helper::IsValidObject(obj) ? obj : nullptr)
ScriptingObjectInterfaceReference(ScriptingObject* obj)
: ScriptingObjectReferenceBase(IsValid(obj) ? obj : nullptr)
{
}
@@ -38,7 +36,7 @@ public:
/// </summary>
/// <param name="interfaceObj">The interface object to link.</param>
ScriptingObjectInterfaceReference(T* interfaceObj)
: ScriptingObjectReferenceBase(Helper::GetSceneObject(interfaceObj))
: ScriptingObjectReferenceBase(ScriptingObject::FromInterface<T>(interfaceObj))
{
}
@@ -64,12 +62,12 @@ public:
}
public:
FORCE_INLINE bool operator==(SceneObject* other) const
FORCE_INLINE bool operator==(ScriptingObject* other) const
{
return _object == other;
}
FORCE_INLINE bool operator!=(SceneObject* other) const
FORCE_INLINE bool operator!=(ScriptingObject* other) const
{
return _object != other;
}
@@ -94,33 +92,34 @@ public:
return _object != other._object;
}
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(SceneObject* other)
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(ScriptingObject* other)
{
OnSet(Helper::IsValidObject(other) ? other : nullptr);
OnSet(IsValid(other) ? other : nullptr);
return *this;
}
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(T* other)
{
OnSet(Helper::GetSceneObject(other));
OnSet(ScriptingObject::FromInterface<T>(other));
return *this;
}
ScriptingObjectInterfaceReference& operator=(const ScriptingObjectInterfaceReference& other)
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(const ScriptingObjectInterfaceReference& other)
{
OnSet(other._object);
return *this;
}
ScriptingObjectInterfaceReference& operator=(ScriptingObjectInterfaceReference&& other) noexcept
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(ScriptingObjectInterfaceReference&& other) noexcept
{
ScriptingObjectReferenceBase::operator=(MoveTemp(other));
return *this;
}
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(const Guid& id)
ScriptingObjectInterfaceReference& operator=(const Guid& id)
{
OnSet(Helper::FindSceneObject(id));
ScriptingObject* obj = FindObject(id, ScriptingObject::GetStaticClass());
OnSet(IsValid(obj) ? obj : nullptr);
return *this;
}
@@ -132,6 +131,14 @@ public:
return Get();
}
/// <summary>
/// Implicit conversion to the object.
/// </summary>
FORCE_INLINE operator ScriptingObject*() const
{
return _object;
}
/// <summary>
/// Implicit conversion to boolean value.
/// </summary>
@@ -159,33 +166,24 @@ public:
/// <summary>
/// Gets the referenced object.
/// </summary>
FORCE_INLINE SceneObject* GetObject() const
FORCE_INLINE ScriptingObject* GetObject() const
{
return static_cast<SceneObject*>(_object);
return _object;
}
/// <summary>
/// Copies the object ID into the raw storage.
/// Gets managed instance object.
/// </summary>
FORCE_INLINE void CopyID(uint32 id[4]) const
FORCE_INLINE MObject* GetManagedInstance() const
{
memset(id, 0, sizeof(uint32) * 4);
if (_object)
{
const Guid value = GetID();
memcpy(id, &value, sizeof(uint32) * 4);
}
return _object ? _object->GetOrCreateManagedInstance() : nullptr;
}
/// <summary>
/// Gets the object as a given type (static cast).
/// </summary>
template<typename U>
FORCE_INLINE U* As() const
private:
FORCE_INLINE static bool IsValid(const ScriptingObject* obj)
{
return static_cast<U*>(_object);
return !obj || obj->GetType().GetInterface(T::TypeInitializer);
}
};
template<typename T>
@@ -1,30 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
#pragma once
#include "Engine/Scripting/ScriptingObjectReference.h"
#include "Engine/Level/SceneObject.h"
/// <summary>
/// Utility methods for scene object interface references.
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
template<typename T>
struct ScriptingObjectInterfaceReferenceHelper
{
FORCE_INLINE static bool IsValidObject(const SceneObject* obj)
{
return !obj || obj->GetType().GetInterface(T::TypeInitializer) != nullptr;
}
FORCE_INLINE static SceneObject* GetSceneObject(T* interfaceObj)
{
return ScriptingObject::Cast<SceneObject>(ScriptingObject::FromInterface<T>(interfaceObj));
}
FORCE_INLINE static SceneObject* FindSceneObject(const Guid& id)
{
SceneObject* obj = static_cast<SceneObject*>(FindObject(id, SceneObject::GetStaticClass()));
return IsValidObject(obj) ? obj : nullptr;
}
};
@@ -72,7 +72,7 @@ public:
}
/// <summary>
/// Gets managed instance object (or null if no object linked).
/// Gets managed instance object.
/// </summary>
FORCE_INLINE MObject* GetManagedInstance() const
{
@@ -1,258 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
#pragma once
#include "Engine/Scripting/SoftObjectReference.h"
#include "Engine/Scripting/ScriptingObjectInterfaceReferenceUtils.h"
/// <summary>
/// The scene object soft interface reference. Objects gets referenced on use (ID reference is resolving it).
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
template<typename T>
API_CLASS(InBuild) class SoftObjectInterfaceReference : public SoftObjectReferenceBase
{
typedef ScriptingObjectInterfaceReferenceHelper<T> Helper;
public:
typedef SoftObjectInterfaceReference<T> Type;
public:
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
SoftObjectInterfaceReference()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="obj">The object to link.</param>
SoftObjectInterfaceReference(SceneObject* obj)
{
OnSet(Helper::IsValidObject(obj) ? obj : nullptr);
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="interfaceObj">The interface object to link.</param>
SoftObjectInterfaceReference(T* interfaceObj)
{
OnSet(Helper::GetSceneObject(interfaceObj));
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="other">The other property.</param>
SoftObjectInterfaceReference(const SoftObjectInterfaceReference& other)
{
OnSet(other.GetID());
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="other">The other property.</param>
SoftObjectInterfaceReference(SoftObjectInterfaceReference&& other)
{
OnSet(other.GetID());
other.OnSet(nullptr);
}
/// <summary>
/// Finalizes an instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
~SoftObjectInterfaceReference()
{
}
public:
FORCE_INLINE bool operator==(SceneObject* other)
{
return GetObject() == other;
}
FORCE_INLINE bool operator!=(SceneObject* other)
{
return GetObject() != other;
}
FORCE_INLINE bool operator==(T* other)
{
return Get() == other;
}
FORCE_INLINE bool operator!=(T* other)
{
return Get() != other;
}
FORCE_INLINE bool operator==(const SoftObjectInterfaceReference& other)
{
return GetID() == other.GetID();
}
FORCE_INLINE bool operator!=(const SoftObjectInterfaceReference& other)
{
return GetID() != other.GetID();
}
SoftObjectInterfaceReference& operator=(const SoftObjectInterfaceReference& other)
{
if (this != &other)
OnSet(other.GetID());
return *this;
}
SoftObjectInterfaceReference& operator=(SoftObjectInterfaceReference&& other)
{
if (this != &other)
{
OnSet(other.GetID());
other.OnSet(nullptr);
}
return *this;
}
FORCE_INLINE SoftObjectInterfaceReference& operator=(SceneObject* other)
{
OnSet(Helper::IsValidObject(other) ? other : nullptr);
return *this;
}
FORCE_INLINE SoftObjectInterfaceReference& operator=(T* other)
{
OnSet(Helper::GetSceneObject(other));
return *this;
}
FORCE_INLINE SoftObjectInterfaceReference& operator=(const Guid& id)
{
OnSet(id);
return *this;
}
/// <summary>
/// Implicit conversion to the interface.
/// </summary>
FORCE_INLINE operator T*() const
{
return Get();
}
/// <summary>
/// Implicit conversion to boolean value.
/// </summary>
FORCE_INLINE operator bool() const
{
return Get() != nullptr;
}
/// <summary>
/// Interface accessor.
/// </summary>
FORCE_INLINE T* operator->() const
{
return Get();
}
/// <summary>
/// Gets the object as a given type (static cast).
/// </summary>
template<typename U>
FORCE_INLINE U* As() const
{
return static_cast<U*>(GetObject());
}
public:
/// <summary>
/// Gets the interface pointer.
/// </summary>
FORCE_INLINE T* Get() const
{
return ScriptingObject::ToInterface<T>(GetObject());
}
/// <summary>
/// Gets the referenced object.
/// </summary>
SceneObject* GetObject() const
{
if (!_object)
const_cast<SoftObjectInterfaceReference*>(this)->OnResolve(SceneObject::GetStaticClass());
return Helper::IsValidObject(static_cast<SceneObject*>(_object)) ? static_cast<SceneObject*>(_object) : nullptr;
}
/// <summary>
/// Gets managed instance object (or null if no object linked).
/// </summary>
MObject* GetManagedInstance() const
{
auto object = GetObject();
return object ? object->GetOrCreateManagedInstance() : nullptr;
}
/// <summary>
/// Determines whether object is assigned and managed instance of the object is alive.
/// </summary>
bool HasManagedInstance() const
{
auto object = GetObject();
return object && object->HasManagedInstance();
}
/// <summary>
/// Gets the managed instance object or creates it if missing or null if not assigned.
/// </summary>
MObject* GetOrCreateManagedInstance() const
{
auto object = GetObject();
return object ? object->GetOrCreateManagedInstance() : nullptr;
}
/// <summary>
/// Copies the object ID into the raw storage.
/// </summary>
FORCE_INLINE void CopyID(uint32 id[4]) const
{
const Guid value = GetID();
memcpy(id, &value, sizeof(uint32) * 4);
}
/// <summary>
/// Sets the object.
/// </summary>
/// <param name="id">The object ID. Uses Scripting to find the registered object of the given ID.</param>
FORCE_INLINE void Set(const Guid& id)
{
OnSet(id);
}
/// <summary>
/// Sets the object.
/// </summary>
/// <param name="object">The object.</param>
FORCE_INLINE void Set(SceneObject* object)
{
OnSet(Helper::IsValidObject(object) ? object : nullptr);
}
/// <summary>
/// Sets the object.
/// </summary>
/// <param name="interfaceObj">The interface object.</param>
FORCE_INLINE void Set(T* interfaceObj)
{
OnSet(Helper::GetSceneObject(interfaceObj));
}
};
template<typename T>
uint32 GetHash(const SoftObjectInterfaceReference<T>& key)
{
return GetHash(key.GetID());
}
@@ -233,7 +233,7 @@ public:
}
/// <summary>
/// Gets managed instance object (or null if no object linked).
/// Gets managed instance object.
/// </summary>
MObject* GetManagedInstance() const
{