MessagePack-CSharp在Unity IL2CPP模式下处理自定义类型序列化的解决方案
问题背景
在使用MessagePack-CSharp进行Unity项目开发时,当切换到IL2CPP编译模式后,开发者可能会遇到一个常见的序列化问题:尝试序列化包含自定义类型数组的对象时,会抛出"Not supported primitive object resolver"异常。这个问题在Mono模式下通常不会出现,但在IL2CPP模式下却会引发错误。
问题分析
问题的核心在于MessagePack-CSharp的PrimitiveObjectFormatter对于非基本类型的处理机制。在IL2CPP环境下,当尝试序列化一个包含自定义类型(如AirSimYawMode、AirSimPose等)的对象数组时,序列化器无法自动识别这些自定义类型,导致序列化失败。
解决方案
要解决这个问题,我们需要创建一个自定义的解析器(Resolver)和格式化器(Formatter),专门用于处理包含自定义类型的对象数组。以下是实现步骤:
1. 创建自定义格式化器
首先,我们需要实现一个IMessagePackFormatter<object[]>接口的自定义格式化器,明确指定如何处理各种类型的数据:
public class CustomObjectArrayFormatter : IMessagePackFormatter<object[]>
{
public void Serialize(ref MessagePackWriter writer, object[] value, MessagePackSerializerOptions options)
{
writer.WriteArrayHeader(value.Length);
foreach (var item in value)
{
switch (item)
{
case int intValue:
writer.Write(intValue);
break;
case float floatValue:
writer.Write(floatValue);
break;
case bool boolValue:
writer.Write(boolValue);
break;
case string stringValue:
writer.Write(stringValue);
break;
case AirSimYawMode yawMode:
options.Resolver.GetFormatterWithVerify<AirSimYawMode>().Serialize(ref writer, yawMode, options);
break;
case AirSimVector vector:
options.Resolver.GetFormatterWithVerify<AirSimVector>().Serialize(ref writer, vector, options);
break;
case AirSimQuaternion quaternion:
options.Resolver.GetFormatterWithVerify<AirSimQuaternion>().Serialize(ref writer, quaternion, options);
break;
case AirSimPose pose:
options.Resolver.GetFormatterWithVerify<AirSimPose>().Serialize(ref writer, pose, options);
break;
default:
throw new InvalidOperationException("Unsupported type encountered: " + item.GetType());
}
}
}
public object[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
var len = reader.ReadArrayHeader();
var result = new object[len];
for (int i = 0; i < len; i++)
{
var type = reader.NextMessagePackType;
switch (type)
{
case MessagePackType.Integer:
result[i] = reader.ReadInt32();
break;
case MessagePackType.Float:
result[i] = reader.ReadSingle();
break;
case MessagePackType.Boolean:
result[i] = reader.ReadBoolean();
break;
case MessagePackType.String:
result[i] = reader.ReadString();
break;
default:
throw new InvalidOperationException("Unsupported MessagePackType encountered: " + type);
}
}
return result;
}
}
2. 注册自定义解析器
接下来,我们需要在应用程序启动时注册这个自定义解析器:
var customize = CompositeResolver.Create(
new IMessagePackFormatter[] { new CustomObjectArrayFormatter() },
new[] { StandardResolver.Instance }
);
StaticCompositeResolver.Instance.Register(
customize,
MessagePack.Resolvers.StandardResolver.Instance,
MessagePack.Resolvers.GeneratedResolver.Instance
);
技术要点
-
类型安全处理:自定义格式化器中通过switch-case语句明确处理每种支持的类型,确保类型安全。
-
性能考虑:直接调用writer.Write方法处理基本类型,避免不必要的反射开销。
-
扩展性:当需要支持新的自定义类型时,只需在格式化器中添加相应的case分支即可。
-
错误处理:对于不支持的类型,抛出明确的异常信息,便于调试。
实际应用
在实际项目中,这种解决方案特别适用于RPC框架或网络通信场景,其中请求/响应对象可能包含各种不同类型的参数。例如:
[MessagePackObject]
public class RpcRequest
{
[Key(0)] public int type { get; set; }
[Key(1)] public int id { get; set; }
[Key(2)] public string method { get; set; }
[Key(3)] public object[] _Param { get; set; }
}
现在,_Param数组可以包含基本类型和自定义类型的混合数据,都能被正确序列化和反序列化。
注意事项
-
确保所有自定义类型都正确标记了[MessagePackObject]和[Key]属性。
-
对于反序列化部分,需要根据实际需求补充对自定义类型的处理逻辑。
-
在性能敏感的场景中,可以考虑进一步优化格式化器的实现,例如使用字典查找替代switch-case。
通过这种解决方案,开发者可以在IL2CPP模式下顺利使用MessagePack-CSharp序列化包含自定义类型的复杂对象,同时保持代码的清晰和可维护性。
Kimi-K2.5Kimi K2.5 是一款开源的原生多模态智能体模型,它在 Kimi-K2-Base 的基础上,通过对约 15 万亿混合视觉和文本 tokens 进行持续预训练构建而成。该模型将视觉与语言理解、高级智能体能力、即时模式与思考模式,以及对话式与智能体范式无缝融合。Python00
GLM-4.7-FlashGLM-4.7-Flash 是一款 30B-A3B MoE 模型。作为 30B 级别中的佼佼者,GLM-4.7-Flash 为追求性能与效率平衡的轻量化部署提供了全新选择。Jinja00
VLOOKVLOOK™ 是优雅好用的 Typora/Markdown 主题包和增强插件。 VLOOK™ is an elegant and practical THEME PACKAGE × ENHANCEMENT PLUGIN for Typora/Markdown.Less00
PaddleOCR-VL-1.5PaddleOCR-VL-1.5 是 PaddleOCR-VL 的新一代进阶模型,在 OmniDocBench v1.5 上实现了 94.5% 的全新 state-of-the-art 准确率。 为了严格评估模型在真实物理畸变下的鲁棒性——包括扫描伪影、倾斜、扭曲、屏幕拍摄和光照变化——我们提出了 Real5-OmniDocBench 基准测试集。实验结果表明,该增强模型在新构建的基准测试集上达到了 SOTA 性能。此外,我们通过整合印章识别和文本检测识别(text spotting)任务扩展了模型的能力,同时保持 0.9B 的超紧凑 VLM 规模,具备高效率特性。Python00
KuiklyUI基于KMP技术的高性能、全平台开发框架,具备统一代码库、极致易用性和动态灵活性。 Provide a high-performance, full-platform development framework with unified codebase, ultimate ease of use, and dynamic flexibility. 注意:本仓库为Github仓库镜像,PR或Issue请移步至Github发起,感谢支持!Kotlin07
compass-metrics-modelMetrics model project for the OSS CompassPython00