桥接与逻辑编写:C#到Lua的数据传递与交互架构
·
桥接与逻辑编写:C#到Lua的数据传递与交互架构
第一部分:C#桥接层架构设计与实现
1.1 桥接层整体架构
在车机系统开发中,C#与Lua的桥接层是性能关键路径,需要精心设计以最小化性能开销。以下是针对高通8155/8295平台的桥接层架构:
// LuaBridgeCore.cs - 桥接层核心架构
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
using UnityEngine.Profiling;
namespace Vehicle.LuaBridge
{
/// <summary>
/// 桥接层配置
/// </summary>
[System.Serializable]
public class BridgeConfig
{
// 性能优化配置
public int maxCacheSize = 1024; // 最大缓存条目数
public bool enableMethodCache = true; // 启用方法缓存
public bool enableObjectPool = true; // 启用对象池
public int objectPoolSize = 100; // 对象池大小
// 内存管理
public bool autoGC = true; // 自动垃圾回收
public int gcThreshold = 50; // GC阈值(MB)
public float gcInterval = 60f; // GC间隔(秒)
// 序列化配置
public bool useBinarySerialization = true; // 使用二进制序列化
public int serializationBufferSize = 1024 * 1024; // 序列化缓冲区大小
// 针对8155/8295的优化
public bool optimizeForAdreno = true; // Adreno GPU优化
public bool useNativeExtensions = true; // 使用原生扩展
}
/// <summary>
/// Lua桥接层核心类
/// </summary>
public class LuaBridgeCore : MonoBehaviour
{
private static LuaBridgeCore instance;
public static LuaBridgeCore Instance
{
get
{
if (instance == null)
{
GameObject go = new GameObject("LuaBridgeCore");
instance = go.AddComponent<LuaBridgeCore>();
DontDestroyOnLoad(go);
}
return instance;
}
}
// 配置
public BridgeConfig config = new BridgeConfig();
// Lua虚拟机引用
private IntPtr luaState = IntPtr.Zero;
// 缓存系统
private ObjectCache objectCache;
private MethodCache methodCache;
private TypeCache typeCache;
// 对象池
private ObjectPoolManager objectPool;
// 序列化器
private ISerializer serializer;
// 性能监控
private BridgePerformanceMonitor perfMonitor;
// 原生扩展(针对高通平台)
private NativeExtension nativeExtension;
void Awake()
{
InitializeBridge();
InitializePerformanceMonitoring();
InitializeNativeExtensions();
}
void Update()
{
UpdateBridge();
// 定期性能检查
if (Time.frameCount % 60 == 0)
{
CheckPerformance();
}
}
void OnDestroy()
{
ShutdownBridge();
}
/// <summary>
/// 初始化桥接层
/// </summary>
private void InitializeBridge()
{
Profiler.BeginSample("LuaBridgeCore.InitializeBridge");
// 创建Lua虚拟机
CreateLuaVM();
// 初始化缓存系统
objectCache = new ObjectCache(config.maxCacheSize);
methodCache = new MethodCache();
typeCache = new TypeCache();
// 初始化对象池
if (config.enableObjectPool)
{
objectPool = new ObjectPoolManager(config.objectPoolSize);
InitializeObjectPools();
}
// 初始化序列化器
if (config.useBinarySerialization)
{
serializer = new BinarySerializer(config.serializationBufferSize);
}
else
{
serializer = new JsonSerializer();
}
// 注册基础类型
RegisterBaseTypes();
// 注册Unity类型
RegisterUnityTypes();
// 注册车机特定类型
RegisterVehicleTypes();
Profiler.EndSample();
Debug.Log("Lua桥接层初始化完成");
}
/// <summary>
/// 创建Lua虚拟机
/// </summary>
private void CreateLuaVM()
{
// 使用Lua原生API创建虚拟机
luaState = LuaNative.luaL_newstate();
if (luaState == IntPtr.Zero)
{
throw new SystemException("无法创建Lua虚拟机");
}
// 加载基础库
LuaNative.luaL_openlibs(luaState);
// 注册C#函数到Lua
RegisterNativeFunctions();
// 加载车机特定Lua库
LoadVehicleLibraries();
}
/// <summary>
/// 初始化性能监控
/// </summary>
private void InitializePerformanceMonitoring()
{
perfMonitor = new BridgePerformanceMonitor();
perfMonitor.StartMonitoring();
}
/// <summary>
/// 初始化原生扩展
/// </summary>
private void InitializeNativeExtensions()
{
if (config.useNativeExtensions)
{
nativeExtension = new NativeExtension();
nativeExtension.Initialize();
}
}
/// <summary>
/// 初始化对象池
/// </summary>
private void InitializeObjectPools()
{
// 预创建常用类型的对象池
objectPool.CreatePool<Vector3>(100, () => Vector3.zero);
objectPool.CreatePool<Quaternion>(100, () => Quaternion.identity);
objectPool.CreatePool<Color>(50, () => Color.white);
objectPool.CreatePool<LuaTable>(200, () => new LuaTable());
objectPool.CreatePool<LuaFunction>(100, () => new LuaFunction());
Debug.Log($"对象池初始化完成,已创建{objectPool.PoolCount}个池");
}
/// <summary>
/// 更新桥接层
/// </summary>
private void UpdateBridge()
{
// 更新性能监控
perfMonitor.Update();
// 自动垃圾回收
if (config.autoGC && Time.time % config.gcInterval < Time.deltaTime)
{
CheckAndRunGC();
}
// 更新缓存(清理过期条目)
objectCache.Cleanup();
// 更新原生扩展
nativeExtension?.Update();
}
/// <summary>
/// 检查和运行垃圾回收
/// </summary>
private void CheckAndRunGC()
{
long luaMemory = GetLuaMemoryUsage();
if (luaMemory > config.gcThreshold * 1024 * 1024)
{
Debug.Log($"Lua内存使用过高({luaMemory / 1024 / 1024}MB),执行GC");
RunLuaGC();
}
}
/// <summary>
/// 获取Lua内存使用情况
/// </summary>
private long GetLuaMemoryUsage()
{
// 通过Lua API获取内存使用
return LuaNative.lua_gc(luaState, LuaNative.LUA_GCCOUNT, 0) * 1024;
}
/// <summary>
/// 运行Lua垃圾回收
/// </summary>
private void RunLuaGC()
{
LuaNative.lua_gc(luaState, LuaNative.LUA_GCCOLLECT, 0);
}
/// <summary>
/// 检查性能
/// </summary>
private void CheckPerformance()
{
var stats = perfMonitor.GetStats();
// 检查性能阈值
if (stats.averageCallTimeMs > 5.0f)
{
Debug.LogWarning($"桥接层调用平均耗时过高: {stats.averageCallTimeMs:F2}ms");
// 自动优化
if (stats.cacheHitRate < 0.7f)
{
Debug.Log("缓存命中率低,正在优化缓存策略...");
OptimizeCacheStrategy();
}
}
}
/// <summary>
/// 优化缓存策略
/// </summary>
private void OptimizeCacheStrategy()
{
// 根据访问模式调整缓存大小
var accessPattern = perfMonitor.GetAccessPattern();
if (accessPattern.hotDataRatio > 0.8f)
{
// 热点数据集中,增加缓存大小
config.maxCacheSize = Mathf.Min(config.maxCacheSize * 2, 8192);
objectCache.Resize(config.maxCacheSize);
}
}
/// <summary>
/// 关闭桥接层
/// </summary>
private void ShutdownBridge()
{
Profiler.BeginSample("LuaBridgeCore.ShutdownBridge");
// 清理对象池
objectPool?.ClearAll();
// 清理缓存
objectCache?.Clear();
methodCache?.Clear();
typeCache?.Clear();
// 关闭Lua虚拟机
if (luaState != IntPtr.Zero)
{
LuaNative.lua_close(luaState);
luaState = IntPtr.Zero;
}
// 关闭原生扩展
nativeExtension?.Shutdown();
// 停止性能监控
perfMonitor?.Stop();
Profiler.EndSample();
Debug.Log("Lua桥接层已关闭");
}
#region 公共API
/// <summary>
/// 将C#对象传递给Lua
/// </summary>
public void PushToLua(string luaVarName, object obj)
{
Profiler.BeginSample("LuaBridgeCore.PushToLua");
try
{
// 检查缓存
if (objectCache.TryGet(luaVarName, out object cached))
{
// 更新缓存值
objectCache.Update(luaVarName, obj);
// 如果值相同,跳过推送
if (object.Equals(cached, obj))
{
Profiler.EndSample();
return;
}
}
else
{
// 添加到缓存
objectCache.Add(luaVarName, obj);
}
// 序列化对象
byte[] serializedData = SerializeObject(obj);
// 推送到Lua
PushSerializedDataToLua(luaVarName, serializedData);
// 记录性能
perfMonitor.RecordCall("PushToLua", 1);
}
catch (Exception ex)
{
Debug.LogError($"推送到Lua失败: {ex.Message}");
throw;
}
finally
{
Profiler.EndSample();
}
}
/// <summary>
/// 从Lua获取对象
/// </summary>
public T PullFromLua<T>(string luaVarName)
{
Profiler.BeginSample("LuaBridgeCore.PullFromLua");
try
{
// 检查缓存
if (objectCache.TryGet(luaVarName, out object cached))
{
perfMonitor.RecordCacheHit();
if (cached is T typedCached)
{
Profiler.EndSample();
return typedCached;
}
}
// 从Lua获取序列化数据
byte[] serializedData = PullSerializedDataFromLua(luaVarName);
// 反序列化对象
T result = DeserializeObject<T>(serializedData);
// 更新缓存
objectCache.AddOrUpdate(luaVarName, result);
// 记录性能
perfMonitor.RecordCall("PullFromLua", 1);
return result;
}
catch (Exception ex)
{
Debug.LogError($"从Lua获取失败: {ex.Message}");
throw;
}
finally
{
Profiler.EndSample();
}
}
/// <summary>
/// 调用Lua函数
/// </summary>
public object CallLuaFunction(string functionName, params object[] args)
{
Profiler.BeginSample("LuaBridgeCore.CallLuaFunction");
try
{
// 检查方法缓存
if (config.enableMethodCache &&
methodCache.TryGet(functionName, out var cachedFunc))
{
perfMonitor.RecordCacheHit();
// 使用缓存的函数引用
return InvokeLuaFunction(cachedFunc, args);
}
// 从Lua获取函数
IntPtr luaFunc = GetLuaFunction(functionName);
if (luaFunc == IntPtr.Zero)
{
throw new ArgumentException($"Lua函数不存在: {functionName}");
}
// 缓存函数引用
methodCache.Add(functionName, luaFunc);
// 调用函数
object result = InvokeLuaFunction(luaFunc, args);
// 记录性能
perfMonitor.RecordCall("CallLuaFunction", 1);
return result;
}
catch (Exception ex)
{
Debug.LogError($"调用Lua函数失败: {ex.Message}");
throw;
}
finally
{
Profiler.EndSample();
}
}
/// <summary>
/// 注册C#方法到Lua
/// </summary>
public void RegisterCFunction(string luaName, Delegate function)
{
Profiler.BeginSample("LuaBridgeCore.RegisterCFunction");
try
{
// 创建C#函数包装器
LuaNative.lua_pushcfunction(luaState, Marshal.GetFunctionPointerForDelegate(function));
LuaNative.lua_setglobal(luaState, luaName);
Debug.Log($"已注册C#函数到Lua: {luaName}");
}
catch (Exception ex)
{
Debug.LogError($"注册C#函数失败: {ex.Message}");
throw;
}
finally
{
Profiler.EndSample();
}
}
/// <summary>
/// 执行Lua代码
/// </summary>
public object ExecuteLuaCode(string code, string chunkName = "chunk")
{
Profiler.BeginSample("LuaBridgeCore.ExecuteLuaCode");
try
{
// 加载代码
int result = LuaNative.luaL_loadbuffer(luaState, code, code.Length, chunkName);
if (result != LuaNative.LUA_OK)
{
string error = LuaNative.lua_tostring(luaState, -1);
throw new LuaException($"Lua代码加载失败: {error}");
}
// 执行代码
result = LuaNative.lua_pcall(luaState, 0, 1, 0);
if (result != LuaNative.LUA_OK)
{
string error = LuaNative.lua_tostring(luaState, -1);
throw new LuaException($"Lua代码执行失败: {error}");
}
// 获取返回值
object returnValue = LuaStackToObject(-1);
// 弹出返回值
LuaNative.lua_pop(luaState, 1);
// 记录性能
perfMonitor.RecordCall("ExecuteLuaCode", 1);
return returnValue;
}
catch (Exception ex)
{
Debug.LogError($"执行Lua代码失败: {ex.Message}");
throw;
}
finally
{
Profiler.EndSample();
}
}
#endregion
#region 内部实现
/// <summary>
/// 序列化对象
/// </summary>
private byte[] SerializeObject(object obj)
{
if (obj == null) return new byte[0];
// 使用对象池获取缓冲区
byte[] buffer = objectPool?.GetBuffer() ?? new byte[config.serializationBufferSize];
try
{
return serializer.Serialize(obj, buffer);
}
finally
{
// 归还缓冲区到对象池
objectPool?.ReturnBuffer(buffer);
}
}
/// <summary>
/// 反序列化对象
/// </summary>
private T DeserializeObject<T>(byte[] data)
{
if (data == null || data.Length == 0)
return default(T);
return serializer.Deserialize<T>(data);
}
/// <summary>
/// 推送序列化数据到Lua
/// </summary>
private void PushSerializedDataToLua(string varName, byte[] data)
{
// 将数据压入Lua栈
LuaNative.lua_pushlstring(luaState, data, data.Length);
// 设置全局变量
LuaNative.lua_setglobal(luaState, varName);
// 调用Lua反序列化函数
ExecuteLuaCode($"{varName} = csharp.deserialize({varName})");
}
/// <summary>
/// 从Lua拉取序列化数据
/// </summary>
private byte[] PullSerializedDataFromLua(string varName)
{
// 调用Lua序列化函数
ExecuteLuaCode($"local serialized = csharp.serialize({varName}) return serialized");
// 从栈顶获取数据
IntPtr dataPtr;
UIntPtr length;
dataPtr = LuaNative.lua_tolstring(luaState, -1, out length);
if (dataPtr == IntPtr.Zero)
return new byte[0];
// 复制数据
byte[] data = new byte[(int)length];
Marshal.Copy(dataPtr, data, 0, (int)length);
// 弹出数据
LuaNative.lua_pop(luaState, 1);
return data;
}
/// <summary>
/// 获取Lua函数
/// </summary>
private IntPtr GetLuaFunction(string functionName)
{
// 获取全局函数
LuaNative.lua_getglobal(luaState, functionName);
if (!LuaNative.lua_isfunction(luaState, -1))
{
LuaNative.lua_pop(luaState, 1);
return IntPtr.Zero;
}
// 获取函数引用
IntPtr funcRef = LuaNative.luaL_ref(luaState, LuaNative.LUA_REGISTRYINDEX);
return funcRef;
}
/// <summary>
/// 调用Lua函数
/// </summary>
private object InvokeLuaFunction(IntPtr funcRef, object[] args)
{
// 获取函数
LuaNative.lua_rawgeti(luaState, LuaNative.LUA_REGISTRYINDEX, funcRef);
// 压入参数
foreach (object arg in args)
{
PushObjectToLuaStack(arg);
}
// 调用函数
int result = LuaNative.lua_pcall(luaState, args.Length, 1, 0);
if (result != LuaNative.LUA_OK)
{
string error = LuaNative.lua_tostring(luaState, -1);
throw new LuaException($"Lua函数调用失败: {error}");
}
// 获取返回值
object returnValue = LuaStackToObject(-1);
// 清理栈
LuaNative.lua_pop(luaState, 1);
return returnValue;
}
/// <summary>
/// 将对象压入Lua栈
/// </summary>
private void PushObjectToLuaStack(object obj)
{
if (obj == null)
{
LuaNative.lua_pushnil(luaState);
return;
}
Type type = obj.GetType();
if (type == typeof(int) || type == typeof(long) || type == typeof(short))
{
LuaNative.lua_pushinteger(luaState, Convert.ToInt64(obj));
}
else if (type == typeof(float) || type == typeof(double))
{
LuaNative.lua_pushnumber(luaState, Convert.ToDouble(obj));
}
else if (type == typeof(bool))
{
LuaNative.lua_pushboolean(luaState, (bool)obj ? 1 : 0);
}
else if (type == typeof(string))
{
LuaNative.lua_pushstring(luaState, (string)obj);
}
else
{
// 复杂类型使用序列化
byte[] data = SerializeObject(obj);
LuaNative.lua_pushlstring(luaState, data, data.Length);
}
}
/// <summary>
/// 从Lua栈获取对象
/// </summary>
private object LuaStackToObject(int index)
{
int type = LuaNative.lua_type(luaState, index);
switch (type)
{
case LuaNative.LUA_TNIL:
return null;
case LuaNative.LUA_TBOOLEAN:
return LuaNative.lua_toboolean(luaState, index) != 0;
case LuaNative.LUA_TNUMBER:
if (LuaNative.lua_isinteger(luaState, index) != 0)
return LuaNative.lua_tointeger(luaState, index);
else
return LuaNative.lua_tonumber(luaState, index);
case LuaNative.LUA_TSTRING:
return LuaNative.lua_tostring(luaState, index);
case LuaNative.LUA_TTABLE:
// 处理Lua表
return LuaTableFromStack(index);
default:
// 其他类型使用反序列化
IntPtr dataPtr;
UIntPtr length;
dataPtr = LuaNative.lua_tolstring(luaState, index, out length);
if (dataPtr != IntPtr.Zero)
{
byte[] data = new byte[(int)length];
Marshal.Copy(dataPtr, data, 0, (int)length);
return serializer.Deserialize<object>(data);
}
return null;
}
}
/// <summary>
/// 从栈创建Lua表
/// </summary>
private LuaTable LuaTableFromStack(int index)
{
LuaTable table = objectPool?.Get<LuaTable>() ?? new LuaTable();
// 遍历表
LuaNative.lua_pushnil(luaState);
while (LuaNative.lua_next(luaState, index) != 0)
{
// 键在-2,值在-1
object key = LuaStackToObject(-2);
object value = LuaStackToObject(-1);
table[key] = value;
// 弹出值,保留键用于下一次迭代
LuaNative.lua_pop(luaState, 1);
}
return table;
}
#endregion
#region 类型注册
/// <summary>
/// 注册基础类型
/// </summary>
private void RegisterBaseTypes()
{
typeCache.RegisterType<int>("int");
typeCache.RegisterType<float>("float");
typeCache.RegisterType<double>("double");
typeCache.RegisterType<bool>("bool");
typeCache.RegisterType<string>("string");
typeCache.RegisterType<byte[]>("bytes");
Debug.Log($"已注册{typeCache.Count}个基础类型");
}
/// <summary>
/// 注册Unity类型
/// </summary>
private void RegisterUnityTypes()
{
typeCache.RegisterType<Vector2>("Vector2");
typeCache.RegisterType<Vector3>("Vector3");
typeCache.RegisterType<Vector4>("Vector4");
typeCache.RegisterType<Quaternion>("Quaternion");
typeCache.RegisterType<Color>("Color");
typeCache.RegisterType<Rect>("Rect");
typeCache.RegisterType<Bounds>("Bounds");
typeCache.RegisterType<Matrix4x4>("Matrix4x4");
Debug.Log($"已注册{typeCache.Count}个Unity类型");
}
/// <summary>
/// 注册车机特定类型
/// </summary>
private void RegisterVehicleTypes()
{
// 车机CAN总线数据
typeCache.RegisterType<CanMessage>("CanMessage");
typeCache.RegisterType<VehicleState>("VehicleState");
typeCache.RegisterType<SensorData>("SensorData");
typeCache.RegisterType<NavigationData>("NavigationData");
typeCache.RegisterType<MediaInfo>("MediaInfo");
// 车机UI数据
typeCache.RegisterType<InstrumentClusterData>("InstrumentClusterData");
typeCache.RegisterType<InfotainmentData>("InfotainmentData");
typeCache.RegisterType<ClimateControlData>("ClimateControlData");
Debug.Log($"已注册{typeCache.Count}个车机特定类型");
}
/// <summary>
/// 注册原生函数
/// </summary>
private void RegisterNativeFunctions()
{
// 注册序列化/反序列化函数
RegisterCFunction("csharp_serialize", new LuaNativeFunction(CSerialize));
RegisterCFunction("csharp_deserialize", new LuaNativeFunction(CDeserialize));
// 注册性能监控函数
RegisterCFunction("csharp_get_perf_stats", new LuaNativeFunction(CGetPerfStats));
// 注册车机特定函数
RegisterVehicleFunctions();
Debug.Log("原生函数注册完成");
}
/// <summary>
/// 注册车机特定函数
/// </summary>
private void RegisterVehicleFunctions()
{
// CAN总线访问
RegisterCFunction("can_read", new LuaNativeFunction(CCanRead));
RegisterCFunction("can_write", new LuaNativeFunction(CCanWrite));
// 传感器访问
RegisterCFunction("sensor_get", new LuaNativeFunction(CSensorGet));
// 车辆控制
RegisterCFunction("vehicle_set_parameter", new LuaNativeFunction(CVehicleSetParameter));
RegisterCFunction("vehicle_get_parameter", new LuaNativeFunction(CVehicleGetParameter));
// 多媒体控制
RegisterCFunction("media_play", new LuaNativeFunction(CMediaPlay));
RegisterCFunction("media_stop", new LuaNativeFunction(CMediaStop));
Debug.Log("车机特定函数注册完成");
}
/// <summary>
/// 加载车机特定Lua库
/// </summary>
private void LoadVehicleLibraries()
{
string[] libraries = {
"vehicle_can",
"vehicle_sensors",
"vehicle_control",
"vehicle_media",
"vehicle_ui"
};
foreach (string lib in libraries)
{
ExecuteLuaCode($"require '{lib}'");
}
Debug.Log("车机Lua库加载完成");
}
#endregion
#region 原生回调函数
// C#序列化回调
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int LuaNativeFunction(IntPtr luaState);
private static int CSerialize(IntPtr luaState)
{
try
{
// 获取参数数量
int argCount = LuaNative.lua_gettop(luaState);
if (argCount != 1)
{
LuaNative.lua_pushstring(luaState, "serialize函数需要1个参数");
return LuaNative.LUA_ERROR;
}
// 获取要序列化的对象
object obj = Instance.LuaStackToObject(1);
// 序列化
byte[] data = Instance.SerializeObject(obj);
// 返回序列化数据
LuaNative.lua_pushlstring(luaState, data, data.Length);
return 1;
}
catch (Exception ex)
{
LuaNative.lua_pushstring(luaState, $"序列化失败: {ex.Message}");
return LuaNative.LUA_ERROR;
}
}
private static int CDeserialize(IntPtr luaState)
{
try
{
// 获取参数数量
int argCount = LuaNative.lua_gettop(luaState);
if (argCount != 1)
{
LuaNative.lua_pushstring(luaState, "deserialize函数需要1个参数");
return LuaNative.LUA_ERROR;
}
// 获取序列化数据
IntPtr dataPtr;
UIntPtr length;
dataPtr = LuaNative.lua_tolstring(luaState, 1, out length);
if (dataPtr == IntPtr.Zero)
{
LuaNative.lua_pushnil(luaState);
return 1;
}
byte[] data = new byte[(int)length];
Marshal.Copy(dataPtr, data, 0, (int)length);
// 反序列化
object obj = Instance.serializer.Deserialize<object>(data);
// 推送到Lua栈
Instance.PushObjectToLuaStack(obj);
return 1;
}
catch (Exception ex)
{
LuaNative.lua_pushstring(luaState, $"反序列化失败: {ex.Message}");
return LuaNative.LUA_ERROR;
}
}
private static int CGetPerfStats(IntPtr luaState)
{
try
{
var stats = Instance.perfMonitor.GetStats();
// 创建Lua表
LuaNative.lua_createtable(luaState, 0, 5);
// 添加统计信息
LuaNative.lua_pushstring(luaState, "total_calls");
LuaNative.lua_pushinteger(luaState, stats.totalCalls);
LuaNative.lua_settable(luaState, -3);
LuaNative.lua_pushstring(luaState, "avg_call_time");
LuaNative.lua_pushnumber(luaState, stats.averageCallTimeMs);
LuaNative.lua_settable(luaState, -3);
LuaNative.lua_pushstring(luaState, "cache_hit_rate");
LuaNative.lua_pushnumber(luaState, stats.cacheHitRate);
LuaNative.lua_settable(luaState, -3);
LuaNative.lua_pushstring(luaState, "memory_usage");
LuaNative.lua_pushinteger(luaState, stats.memoryUsage);
LuaNative.lua_settable(luaState, -3);
LuaNative.lua_pushstring(luaState, "active_connections");
LuaNative.lua_pushinteger(luaState, stats.activeConnections);
LuaNative.lua_settable(luaState, -3);
return 1;
}
catch (Exception ex)
{
LuaNative.lua_pushstring(luaState, $"获取性能统计失败: {ex.Message}");
return LuaNative.LUA_ERROR;
}
}
// 车机特定回调函数
private static int CCanRead(IntPtr luaState)
{
// CAN总线读取实现
// ...
return 1;
}
private static int CCanWrite(IntPtr luaState)
{
// CAN总线写入实现
// ...
return 1;
}
private static int CSensorGet(IntPtr luaState)
{
// 传感器数据获取实现
// ...
return 1;
}
#endregion
}
/// <summary>
/// Lua异常
/// </summary>
public class LuaException : Exception
{
public LuaException(string message) : base(message) { }
public LuaException(string message, Exception inner) : base(message, inner) { }
}
/// <summary>
/// Lua表包装类
/// </summary>
public class LuaTable : IDisposable
{
private Dictionary<object, object> table = new Dictionary<object, object>();
public object this[object key]
{
get { return table.ContainsKey(key) ? table[key] : null; }
set { table[key] = value; }
}
public void Dispose()
{
table.Clear();
}
}
/// <summary>
/// Lua函数包装类
/// </summary>
public class LuaFunction : IDisposable
{
public IntPtr FunctionRef { get; set; }
public void Dispose()
{
// 释放Lua函数引用
}
}
}
1.2 缓存系统实现
// ObjectCache.cs - 对象缓存系统
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Vehicle.LuaBridge
{
/// <summary>
/// 对象缓存项
/// </summary>
public class CacheItem
{
public string Key { get; set; }
public object Value { get; set; }
public DateTime LastAccess { get; set; }
public int AccessCount { get; set; }
public long Size { get; set; }
public bool IsPinned { get; set; }
public CacheItem(string key, object value)
{
Key = key;
Value = value;
LastAccess = DateTime.Now;
AccessCount = 1;
Size = EstimateSize(value);
}
private long EstimateSize(object obj)
{
if (obj == null) return 0;
// 简单的大小估算
Type type = obj.GetType();
if (type.IsValueType)
{
return System.Runtime.InteropServices.Marshal.SizeOf(obj);
}
else if (type == typeof(string))
{
return System.Text.Encoding.UTF8.GetByteCount((string)obj);
}
else
{
// 复杂类型使用近似估算
return 100; // 默认100字节
}
}
public void UpdateAccess()
{
LastAccess = DateTime.Now;
AccessCount++;
}
}
/// <summary>
/// 对象缓存系统
/// </summary>
public class ObjectCache
{
private Dictionary<string, CacheItem> cache = new Dictionary<string, CacheItem>();
private LinkedList<string> accessOrder = new LinkedList<string>();
private int maxSize;
private long currentSize;
// 性能统计
private int hitCount;
private int missCount;
private int evictionCount;
public ObjectCache(int maxSize = 1024)
{
this.maxSize = maxSize;
this.currentSize = 0;
}
/// <summary>
/// 尝试获取缓存项
/// </summary>
public bool TryGet(string key, out object value)
{
if (cache.TryGetValue(key, out CacheItem item))
{
// 更新访问记录
item.UpdateAccess();
UpdateAccessOrder(key);
hitCount++;
value = item.Value;
return true;
}
missCount++;
value = null;
return false;
}
/// <summary>
/// 添加缓存项
/// </summary>
public void Add(string key, object value)
{
if (cache.ContainsKey(key))
{
Update(key, value);
return;
}
CacheItem item = new CacheItem(key, value);
cache[key] = item;
currentSize += item.Size;
// 添加到访问顺序列表
accessOrder.AddFirst(key);
// 检查是否需要清理
if (cache.Count > maxSize || currentSize > maxSize * 1024 * 1024)
{
Evict();
}
}
/// <summary>
/// 更新缓存项
/// </summary>
public void Update(string key, object value)
{
if (cache.TryGetValue(key, out CacheItem oldItem))
{
// 更新大小
currentSize -= oldItem.Size;
CacheItem newItem = new CacheItem(key, value);
currentSize += newItem.Size;
// 替换缓存项
cache[key] = newItem;
UpdateAccessOrder(key);
}
else
{
Add(key, value);
}
}
/// <summary>
/// 添加或更新缓存项
/// </summary>
public void AddOrUpdate(string key, object value)
{
if (cache.ContainsKey(key))
Update(key, value);
else
Add(key, value);
}
/// <summary>
/// 移除缓存项
/// </summary>
public bool Remove(string key)
{
if (cache.TryGetValue(key, out CacheItem item))
{
cache.Remove(key);
currentSize -= item.Size;
accessOrder.Remove(key);
return true;
}
return false;
}
/// <summary>
/// 清理缓存
/// </summary>
public void Clear()
{
cache.Clear();
accessOrder.Clear();
currentSize = 0;
hitCount = 0;
missCount = 0;
evictionCount = 0;
}
/// <summary>
/// 清理过期条目
/// </summary>
public void Cleanup()
{
List<string> toRemove = new List<string>();
DateTime now = DateTime.Now;
foreach (var kvp in cache)
{
CacheItem item = kvp.Value;
// 清理超过1小时未访问的非固定项
if (!item.IsPinned && (now - item.LastAccess).TotalHours > 1)
{
toRemove.Add(kvp.Key);
}
}
foreach (string key in toRemove)
{
Remove(key);
evictionCount++;
}
if (toRemove.Count > 0)
{
Debug.Log($"缓存清理完成,移除了{toRemove.Count}个过期条目");
}
}
/// <summary>
/// 调整缓存大小
/// </summary>
public void Resize(int newSize)
{
maxSize = newSize;
// 如果当前大小超过新限制,执行清理
while (cache.Count > maxSize)
{
Evict();
}
}
/// <summary>
/// 淘汰缓存项
/// </summary>
private void Evict()
{
if (accessOrder.Count == 0)
return;
// 使用LRU策略:移除最近最少使用的非固定项
LinkedListNode<string> node = accessOrder.Last;
while (node != null)
{
string key = node.Value;
LinkedListNode<string> prevNode = node.Previous;
if (cache.TryGetValue(key, out CacheItem item))
{
if (!item.IsPinned)
{
Remove(key);
evictionCount++;
Debug.Log($"淘汰缓存项: {key} (大小: {item.Size}字节)");
break;
}
}
node = prevNode;
}
}
/// <summary>
/// 更新访问顺序
/// </summary>
private void UpdateAccessOrder(string key)
{
// 移除旧的节点
accessOrder.Remove(key);
// 添加到头部(最近使用)
accessOrder.AddFirst(key);
}
/// <summary>
/// 获取缓存统计信息
/// </summary>
public CacheStats GetStats()
{
float hitRate = (hitCount + missCount) > 0 ?
(float)hitCount / (hitCount + missCount) : 0;
return new CacheStats
{
TotalItems = cache.Count,
CurrentSize = currentSize,
HitCount = hitCount,
MissCount = missCount,
HitRate = hitRate,
EvictionCount = evictionCount
};
}
/// <summary>
/// 缓存统计信息
/// </summary>
public struct CacheStats
{
public int TotalItems;
public long CurrentSize;
public int HitCount;
public int MissCount;
public float HitRate;
public int EvictionCount;
}
/// <summary>
/// 固定缓存项(防止被淘汰)
/// </summary>
public void Pin(string key)
{
if (cache.TryGetValue(key, out CacheItem item))
{
item.IsPinned = true;
}
}
/// <summary>
/// 解固定缓存项
/// </summary>
public void Unpin(string key)
{
if (cache.TryGetValue(key, out CacheItem item))
{
item.IsPinned = false;
}
}
}
/// <summary>
/// 方法缓存系统
/// </summary>
public class MethodCache
{
private Dictionary<string, IntPtr> cache = new Dictionary<string, IntPtr>();
public bool TryGet(string methodName, out IntPtr functionRef)
{
return cache.TryGetValue(methodName, out functionRef);
}
public void Add(string methodName, IntPtr functionRef)
{
cache[methodName] = functionRef;
}
public bool Remove(string methodName)
{
return cache.Remove(methodName);
}
public void Clear()
{
cache.Clear();
}
}
/// <summary>
/// 类型缓存系统
/// </summary>
public class TypeCache
{
private Dictionary<string, Type> typeByName = new Dictionary<string, Type>();
private Dictionary<Type, string> nameByType = new Dictionary<Type, string>();
public int Count => typeByName.Count;
public void RegisterType<T>(string typeName)
{
Type type = typeof(T);
typeByName[typeName] = type;
nameByType[type] = typeName;
}
public bool TryGetType(string typeName, out Type type)
{
return typeByName.TryGetValue(typeName, out type);
}
public bool TryGetName(Type type, out string typeName)
{
return nameByType.TryGetValue(type, out typeName);
}
public void Clear()
{
typeByName.Clear();
nameByType.Clear();
}
}
}
1.3 序列化系统实现
// Serializer.cs - 序列化系统
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
namespace Vehicle.LuaBridge
{
/// <summary>
/// 序列化器接口
/// </summary>
public interface ISerializer
{
byte[] Serialize(object obj, byte[] buffer = null);
T Deserialize<T>(byte[] data);
}
/// <summary>
/// 二进制序列化器(高性能)
/// </summary>
public class BinarySerializer : ISerializer
{
private BinaryFormatter formatter;
private MemoryStream stream;
private byte[] defaultBuffer;
public BinarySerializer(int bufferSize = 1024 * 1024)
{
formatter = new BinaryFormatter();
stream = new MemoryStream(bufferSize);
defaultBuffer = new byte[bufferSize];
}
public byte[] Serialize(object obj, byte[] buffer = null)
{
if (obj == null)
return new byte[0];
try
{
stream.Seek(0, SeekOrigin.Begin);
stream.SetLength(0);
// 使用提供的缓冲区或默认缓冲区
if (buffer != null && buffer.Length >= stream.Capacity)
{
stream.SetLength(buffer.Length);
stream.Write(buffer, 0, buffer.Length);
stream.Seek(0, SeekOrigin.Begin);
}
formatter.Serialize(stream, obj);
// 返回序列化数据
byte[] result = new byte[stream.Position];
Array.Copy(stream.GetBuffer(), 0, result, 0, (int)stream.Position);
return result;
}
catch (Exception ex)
{
Debug.LogError($"二进制序列化失败: {ex.Message}");
throw;
}
}
public T Deserialize<T>(byte[] data)
{
if (data == null || data.Length == 0)
return default(T);
try
{
stream.Seek(0, SeekOrigin.Begin);
stream.Write(data, 0, data.Length);
stream.Seek(0, SeekOrigin.Begin);
object obj = formatter.Deserialize(stream);
if (obj is T)
{
return (T)obj;
}
else
{
Debug.LogError($"反序列化类型不匹配: 期望{typeof(T).Name}, 实际{obj.GetType().Name}");
return default(T);
}
}
catch (Exception ex)
{
Debug.LogError($"二进制反序列化失败: {ex.Message}");
throw;
}
}
public void Dispose()
{
stream?.Close();
stream = null;
}
}
/// <summary>
/// JSON序列化器(兼容性好)
/// </summary>
public class JsonSerializer : ISerializer
{
public byte[] Serialize(object obj, byte[] buffer = null)
{
if (obj == null)
return new byte[0];
try
{
string json = JsonUtility.ToJson(obj);
return System.Text.Encoding.UTF8.GetBytes(json);
}
catch (Exception ex)
{
Debug.LogError($"JSON序列化失败: {ex.Message}");
throw;
}
}
public T Deserialize<T>(byte[] data)
{
if (data == null || data.Length == 0)
return default(T);
try
{
string json = System.Text.Encoding.UTF8.GetString(data);
return JsonUtility.FromJson<T>(json);
}
catch (Exception ex)
{
Debug.LogError($"JSON反序列化失败: {ex.Message}");
throw;
}
}
}
/// <summary>
/// 针对车机数据的优化序列化器
/// </summary>
public class VehicleDataSerializer : ISerializer
{
private BinarySerializer binarySerializer;
private Dictionary<Type, IVehicleDataConverter> converters;
public VehicleDataSerializer()
{
binarySerializer = new BinarySerializer();
converters = new Dictionary<Type, IVehicleDataConverter>();
// 注册车机数据类型转换器
RegisterConverters();
}
private void RegisterConverters()
{
converters[typeof(CanMessage)] = new CanMessageConverter();
converters[typeof(VehicleState)] = new VehicleStateConverter();
converters[typeof(SensorData)] = new SensorDataConverter();
converters[typeof(NavigationData)] = new NavigationDataConverter();
// 注册Unity类型转换器
converters[typeof(Vector3)] = new Vector3Converter();
converters[typeof(Quaternion)] = new QuaternionConverter();
converters[typeof(Color)] = new ColorConverter();
}
public byte[] Serialize(object obj, byte[] buffer = null)
{
if (obj == null)
return new byte[0];
Type type = obj.GetType();
// 检查是否有专用的转换器
if (converters.TryGetValue(type, out IVehicleDataConverter converter))
{
return converter.Serialize(obj, buffer);
}
// 回退到二进制序列化
return binarySerializer.Serialize(obj, buffer);
}
public T Deserialize<T>(byte[] data)
{
if (data == null || data.Length == 0)
return default(T);
Type type = typeof(T);
// 检查是否有专用的转换器
if (converters.TryGetValue(type, out IVehicleDataConverter converter))
{
return (T)converter.Deserialize(data);
}
// 回退到二进制反序列化
return binarySerializer.Deserialize<T>(data);
}
public void Dispose()
{
binarySerializer?.Dispose();
converters?.Clear();
}
}
/// <summary>
/// 车机数据转换器接口
/// </summary>
public interface IVehicleDataConverter
{
byte[] Serialize(object obj, byte[] buffer = null);
object Deserialize(byte[] data);
}
/// <summary>
/// CAN消息转换器
/// </summary>
public class CanMessageConverter : IVehicleDataConverter
{
public byte[] Serialize(object obj, byte[] buffer = null)
{
if (!(obj is CanMessage message))
throw new ArgumentException("对象必须是CanMessage类型");
// CAN消息的紧凑序列化格式
// 格式: [ID(4字节)][DLC(1字节)][数据(0-8字节)][时间戳(8字节)]
int dataLength = Math.Min(message.Data.Length, 8);
int totalLength = 4 + 1 + dataLength + 8;
byte[] result = buffer != null && buffer.Length >= totalLength ?
buffer : new byte[totalLength];
using (MemoryStream stream = new MemoryStream(result))
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(message.Id);
writer.Write((byte)dataLength);
writer.Write(message.Data, 0, dataLength);
writer.Write(message.Timestamp);
}
return result;
}
public object Deserialize(byte[] data)
{
if (data == null || data.Length < 13) // 最小长度: ID(4) + DLC(1) + 时间戳(8)
return new CanMessage();
using (MemoryStream stream = new MemoryStream(data))
using (BinaryReader reader = new BinaryReader(stream))
{
uint id = reader.ReadUInt32();
byte dlc = reader.ReadByte();
byte[] messageData = new byte[dlc];
reader.Read(messageData, 0, dlc);
long timestamp = reader.ReadInt64();
return new CanMessage
{
Id = id,
Data = messageData,
Timestamp = timestamp
};
}
}
}
/// <summary>
/// Vector3转换器(优化版)
/// </summary>
public class Vector3Converter : IVehicleDataConverter
{
public byte[] Serialize(object obj, byte[] buffer = null)
{
if (!(obj is Vector3 vector))
throw new ArgumentException("对象必须是Vector3类型");
byte[] result = buffer != null && buffer.Length >= 12 ?
buffer : new byte[12];
unsafe
{
fixed (byte* pResult = result)
{
float* pFloat = (float*)pResult;
pFloat[0] = vector.x;
pFloat[1] = vector.y;
pFloat[2] = vector.z;
}
}
return result;
}
public object Deserialize(byte[] data)
{
if (data == null || data.Length < 12)
return Vector3.zero;
unsafe
{
fixed (byte* pData = data)
{
float* pFloat = (float*)pData;
return new Vector3(pFloat[0], pFloat[1], pFloat[2]);
}
}
}
}
/// <summary>
/// CAN消息数据结构
/// </summary>
[Serializable]
public struct CanMessage
{
public uint Id;
public byte[] Data;
public long Timestamp;
}
}
第二部分:数据反序列化与传递
2.1 反序列化数据处理
// DataDeserializer.cs - 反序列化数据处理器
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace Vehicle.LuaBridge
{
/// <summary>
/// 反序列化配置
/// </summary>
[System.Serializable]
public class DeserializerConfig
{
public bool validateChecksum = true; // 验证校验和
public bool decompressData = true; // 解压缩数据
public bool cacheDeserialized = true; // 缓存反序列化结果
public int maxCacheSize = 100; // 最大缓存大小
public float timeoutSeconds = 5.0f; // 超时时间
}
/// <summary>
/// 数据反序列化器
/// </summary>
public class DataDeserializer : MonoBehaviour
{
public DeserializerConfig config = new DeserializerConfig();
private ISerializer serializer;
private DeserializerCache cache;
private DataValidator validator;
private DataCompressor compressor;
// 性能监控
private int deserializationCount;
private long totalDeserializationTimeMs;
private int errorCount;
void Awake()
{
Initialize();
}
void Initialize()
{
// 初始化序列化器
serializer = new VehicleDataSerializer();
// 初始化缓存
if (config.cacheDeserialized)
{
cache = new DeserializerCache(config.maxCacheSize);
}
// 初始化验证器
if (config.validateChecksum)
{
validator = new DataValidator();
}
// 初始化压缩器
if (config.decompressData)
{
compressor = new DataCompressor();
}
Debug.Log("数据反序列化器初始化完成");
}
/// <summary>
/// 反序列化原始数据
/// </summary>
public T Deserialize<T>(byte[] rawData, string dataId = null)
{
Profiler.BeginSample("DataDeserializer.Deserialize");
try
{
// 检查缓存
if (config.cacheDeserialized && !string.IsNullOrEmpty(dataId))
{
if (cache.TryGet<T>(dataId, out T cachedResult))
{
Profiler.EndSample();
return cachedResult;
}
}
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
// 预处理数据
byte[] processedData = PreprocessData(rawData);
// 验证数据
if (!ValidateData(processedData))
{
throw new DataValidationException("数据验证失败");
}
// 反序列化
T result = serializer.Deserialize<T>(processedData);
stopwatch.Stop();
// 更新统计
deserializationCount++;
totalDeserializationTimeMs += stopwatch.ElapsedMilliseconds;
// 缓存结果
if (config.cacheDeserialized && !string.IsNullOrEmpty(dataId))
{
cache.Add(dataId, result);
}
// 记录性能
RecordPerformance(stopwatch.ElapsedMilliseconds, processedData.Length);
return result;
}
catch (Exception ex)
{
errorCount++;
Debug.LogError($"反序列化失败: {ex.Message}");
throw;
}
finally
{
Profiler.EndSample();
}
}
/// <summary>
/// 批量反序列化
/// </summary>
public List<T> BatchDeserialize<T>(List<byte[]> rawDataList, List<string> dataIds = null)
{
Profiler.BeginSample("DataDeserializer.BatchDeserialize");
try
{
List<T> results = new List<T>(rawDataList.Count);
for (int i = 0; i < rawDataList.Count; i++)
{
string dataId = dataIds != null && i < dataIds.Count ? dataIds[i] : null;
try
{
T result = Deserialize<T>(rawDataList[i], dataId);
results.Add(result);
}
catch (Exception ex)
{
Debug.LogWarning($"批量反序列化第{i}项失败: {ex.Message}");
results.Add(default(T));
}
}
return results;
}
finally
{
Profiler.EndSample();
}
}
/// <summary>
/// 预处理数据
/// </summary>
private byte[] PreprocessData(byte[] rawData)
{
if (rawData == null || rawData.Length == 0)
return rawData;
byte[] processedData = rawData;
// 解压缩
if (config.decompressData && compressor != null)
{
try
{
processedData = compressor.Decompress(processedData);
}
catch (Exception ex)
{
Debug.LogWarning($"数据解压缩失败: {ex.Message},使用原始数据");
}
}
return processedData;
}
/// <summary>
/// 验证数据
/// </summary>
private bool ValidateData(byte[] data)
{
if (data == null || data.Length == 0)
return false;
if (config.validateChecksum && validator != null)
{
return validator.Validate(data);
}
return true;
}
/// <summary>
/// 记录性能数据
/// </summary>
private void RecordPerformance(long elapsedMs, int dataSize)
{
// 这里可以记录到性能监控系统
if (elapsedMs > 100) // 超过100ms警告
{
Debug.LogWarning($"反序列化耗时过长: {elapsedMs}ms, 数据大小: {dataSize}字节");
}
}
/// <summary>
/// 获取性能统计
/// </summary>
public DeserializerStats GetStats()
{
float avgTime = deserializationCount > 0 ?
(float)totalDeserializationTimeMs / deserializationCount : 0;
return new DeserializerStats
{
TotalDeserializations = deserializationCount,
AverageTimeMs = avgTime,
ErrorCount = errorCount,
CacheHitRate = cache?.HitRate ?? 0,
CacheSize = cache?.Size ?? 0
};
}
/// <summary>
/// 清理缓存
/// </summary>
public void ClearCache()
{
cache?.Clear();
Debug.Log("反序列化缓存已清理");
}
/// <summary>
/// 预加载缓存
/// </summary>
public void PreloadCache<T>(Dictionary<string, byte[]> dataMap)
{
if (cache == null || dataMap == null)
return;
int loadedCount = 0;
foreach (var kvp in dataMap)
{
try
{
T result = Deserialize<T>(kvp.Value, kvp.Key);
loadedCount++;
}
catch (Exception ex)
{
Debug.LogWarning($"预加载缓存失败: {kvp.Key} - {ex.Message}");
}
}
Debug.Log($"缓存预加载完成,成功加载{loadedCount}/{dataMap.Count}项");
}
}
/// <summary>
/// 反序列化统计信息
/// </summary>
public struct DeserializerStats
{
public int TotalDeserializations;
public float AverageTimeMs;
public int ErrorCount;
public float CacheHitRate;
public int CacheSize;
}
/// <summary>
/// 反序列化缓存
/// </summary>
public class DeserializerCache
{
private Dictionary<string, CacheEntry> cache = new Dictionary<string, CacheEntry>();
private int maxSize;
private int hitCount;
private int missCount;
public int Size => cache.Count;
public float HitRate => (hitCount + missCount) > 0 ?
(float)hitCount / (hitCount + missCount) : 0;
public DeserializerCache(int maxSize = 100)
{
this.maxSize = maxSize;
}
public bool TryGet<T>(string key, out T value)
{
if (cache.TryGetValue(key, out CacheEntry entry))
{
// 检查类型是否匹配
if (entry.Value is T typedValue)
{
hitCount++;
entry.LastAccess = DateTime.Now;
value = typedValue;
return true;
}
}
missCount++;
value = default(T);
return false;
}
public void Add(string key, object value)
{
if (cache.Count >= maxSize)
{
// 移除最旧的项目
RemoveOldest();
}
cache[key] = new CacheEntry
{
Value = value,
LastAccess = DateTime.Now,
Type = value?.GetType()
};
}
public bool Remove(string key)
{
return cache.Remove(key);
}
public void Clear()
{
cache.Clear();
hitCount = 0;
missCount = 0;
}
private void RemoveOldest()
{
string oldestKey = null;
DateTime oldestTime = DateTime.MaxValue;
foreach (var kvp in cache)
{
if (kvp.Value.LastAccess < oldestTime)
{
oldestTime = kvp.Value.LastAccess;
oldestKey = kvp.Key;
}
}
if (oldestKey != null)
{
cache.Remove(oldestKey);
}
}
private class CacheEntry
{
public object Value { get; set; }
public DateTime LastAccess { get; set; }
public Type Type { get; set; }
}
}
/// <summary>
/// 数据验证器
/// </summary>
public class DataValidator
{
public bool Validate(byte[] data)
{
if (data == null || data.Length < 4)
return false;
// 检查校验和
uint calculatedChecksum = CalculateChecksum(data, 0, data.Length - 4);
uint storedChecksum = BitConverter.ToUInt32(data, data.Length - 4);
return calculatedChecksum == storedChecksum;
}
public byte[] AddChecksum(byte[] data)
{
if (data == null)
return null;
uint checksum = CalculateChecksum(data, 0, data.Length);
byte[] result = new byte[data.Length + 4];
Array.Copy(data, 0, result, 0, data.Length);
BitConverter.GetBytes(checksum).CopyTo(result, data.Length);
return result;
}
private uint CalculateChecksum(byte[] data, int offset, int length)
{
uint checksum = 0;
for (int i = offset; i < offset + length; i++)
{
checksum = (checksum << 5) + checksum + data[i];
}
return checksum;
}
}
/// <summary>
/// 数据压缩器
/// </summary>
public class DataCompressor
{
public byte[] Compress(byte[] data)
{
if (data == null || data.Length == 0)
return data;
using (MemoryStream output = new MemoryStream())
{
using (System.IO.Compression.GZipStream gzip =
new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionLevel.Optimal))
{
gzip.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
public byte[] Decompress(byte[] compressedData)
{
if (compressedData == null || compressedData.Length == 0)
return compressedData;
using (MemoryStream input = new MemoryStream(compressedData))
using (System.IO.Compression.GZipStream gzip =
new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
using (MemoryStream output = new MemoryStream())
{
gzip.CopyTo(output);
return output.ToArray();
}
}
}
/// <summary>
/// 数据验证异常
/// </summary>
public class DataValidationException : Exception
{
public DataValidationException(string message) : base(message) { }
public DataValidationException(string message, Exception inner) : base(message, inner) { }
}
}
2.2 数据传递管理器
// DataTransferManager.cs - 数据传递管理器
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace Vehicle.LuaBridge
{
/// <summary>
/// 数据传输配置
/// </summary>
[System.Serializable]
public class TransferConfig
{
public int maxQueueSize = 1000; // 最大队列大小
public int batchSize = 50; // 批处理大小
public float batchInterval = 0.1f; // 批处理间隔(秒)
public bool useAsyncTransfer = true; // 使用异步传输
public int maxConcurrentTransfers = 4; // 最大并发传输数
public bool enableCompression = true; // 启用压缩
public int compressionThreshold = 1024; // 压缩阈值(字节)
}
/// <summary>
/// 数据传输管理器
/// </summary>
public class DataTransferManager : MonoBehaviour
{
public TransferConfig config = new TransferConfig();
// 数据传输队列
private ConcurrentQueue<TransferRequest> transferQueue = new ConcurrentQueue<TransferRequest>();
private ConcurrentQueue<TransferResult> resultQueue = new ConcurrentQueue<TransferResult>();
// 批处理
private List<TransferRequest> currentBatch = new List<TransferRequest>();
private float nextBatchTime = 0;
// 异步处理
private CancellationTokenSource cancellationTokenSource;
private List<Task> transferTasks = new List<Task>();
private SemaphoreSlim transferSemaphore;
// 性能监控
private TransferStats stats = new TransferStats();
private System.Diagnostics.Stopwatch batchTimer = new System.Diagnostics.Stopwatch();
// 桥接层引用
private LuaBridgeCore bridgeCore;
void Awake()
{
Initialize();
}
void Initialize()
{
bridgeCore = LuaBridgeCore.Instance;
// 初始化异步处理
if (config.useAsyncTransfer)
{
cancellationTokenSource = new CancellationTokenSource();
transferSemaphore = new SemaphoreSlim(config.maxConcurrentTransfers);
StartAsyncProcessors();
}
Debug.Log("数据传输管理器初始化完成");
}
void Update()
{
// 处理同步传输
if (!config.useAsyncTransfer)
{
ProcessTransfers();
}
// 处理结果
ProcessResults();
// 性能监控
UpdateStats();
}
void OnDestroy()
{
// 停止异步处理
if (config.useAsyncTransfer)
{
cancellationTokenSource?.Cancel();
try
{
Task.WaitAll(transferTasks.ToArray(), 5000);
}
catch (AggregateException)
{
// 忽略任务取消异常
}
cancellationTokenSource?.Dispose();
transferSemaphore?.Dispose();
}
}
/// <summary>
/// 启动异步处理器
/// </summary>
private void StartAsyncProcessors()
{
for (int i = 0; i < config.maxConcurrentTransfers; i++)
{
Task task = Task.Run(async () => await ProcessTransfersAsync(cancellationTokenSource.Token));
transferTasks.Add(task);
}
Debug.Log($"启动了{config.maxConcurrentTransfers}个异步处理器");
}
/// <summary>
/// 提交数据传输请求
/// </summary>
public string SubmitTransfer(string luaVarName, object data,
TransferPriority priority = TransferPriority.Normal)
{
string requestId = Guid.NewGuid().ToString();
var request = new TransferRequest
{
RequestId = requestId,
LuaVarName = luaVarName,
Data = data,
Priority = priority,
SubmitTime = DateTime.Now
};
// 检查队列大小
if (transferQueue.Count >= config.maxQueueSize)
{
// 队列已满,尝试移除低优先级项目
if (!TryMakeRoomForRequest(request))
{
stats.DroppedRequests++;
throw new TransferQueueFullException($"传输队列已满,无法提交请求: {requestId}");
}
}
transferQueue.Enqueue(request);
stats.SubmittedRequests++;
return requestId;
}
/// <summary>
/// 批量提交数据传输请求
/// </summary>
public List<string> SubmitBatchTransfer(List<TransferBatchItem> batchItems)
{
List<string> requestIds = new List<string>();
foreach (var item in batchItems)
{
try
{
string requestId = SubmitTransfer(item.LuaVarName, item.Data, item.Priority);
requestIds.Add(requestId);
}
catch (TransferQueueFullException)
{
// 队列已满,跳过剩余项目
Debug.LogWarning("传输队列已满,跳过批量传输的剩余项目");
break;
}
}
return requestIds;
}
/// <summary>
/// 检查传输状态
/// </summary>
public TransferStatus CheckStatus(string requestId)
{
// 这里可以实现更复杂的状态跟踪
return TransferStatus.Completed; // 简化实现
}
/// <summary>
/// 尝试为请求腾出空间
/// </summary>
private bool TryMakeRoomForRequest(TransferRequest newRequest)
{
// 尝试移除低优先级的项目
if (newRequest.Priority == TransferPriority.High)
{
// 对于高优先级请求,可以移除正常或低优先级项目
return TryRemoveLowPriorityItems(TransferPriority.Normal);
}
else if (newRequest.Priority == TransferPriority.Normal)
{
// 对于正常优先级请求,只移除低优先级项目
return TryRemoveLowPriorityItems(TransferPriority.Low);
}
// 低优先级请求无法腾出空间
return false;
}
/// <summary>
/// 尝试移除低优先级项目
/// </summary>
private bool TryRemoveLowPriorityItems(TransferPriority maxPriorityToRemove)
{
// 简化实现:检查队列中的项目并移除低优先级项目
// 实际实现可能需要遍历队列
return false; // 简化返回
}
/// <summary>
/// 处理传输(同步)
/// </summary>
private void ProcessTransfers()
{
if (transferQueue.IsEmpty)
return;
// 批处理逻辑
if (Time.time >= nextBatchTime)
{
ProcessBatch();
nextBatchTime = Time.time + config.batchInterval;
}
}
/// <summary>
/// 处理批处理
/// </summary>
private void ProcessBatch()
{
batchTimer.Restart();
// 收集批处理项目
int batchCount = 0;
while (batchCount < config.batchSize && transferQueue.TryDequeue(out TransferRequest request))
{
currentBatch.Add(request);
batchCount++;
}
if (currentBatch.Count == 0)
return;
try
{
// 处理批处理
foreach (var request in currentBatch)
{
ProcessSingleTransfer(request);
}
batchTimer.Stop();
stats.LastBatchTimeMs = batchTimer.ElapsedMilliseconds;
stats.ProcessedBatches++;
}
catch (Exception ex)
{
Debug.LogError($"批处理失败: {ex.Message}");
stats.FailedBatches++;
}
finally
{
currentBatch.Clear();
}
}
/// <summary>
/// 异步处理传输
/// </summary>
private async Task ProcessTransfersAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
// 等待信号量
await transferSemaphore.WaitAsync(cancellationToken);
if (transferQueue.TryDequeue(out TransferRequest request))
{
// 处理传输
await ProcessSingleTransferAsync(request, cancellationToken);
}
// 短暂休眠避免忙等待
await Task.Delay(1, cancellationToken);
}
catch (OperationCanceledException)
{
// 任务被取消
break;
}
catch (Exception ex)
{
Debug.LogError($"异步传输处理失败: {ex.Message}");
}
finally
{
transferSemaphore.Release();
}
}
}
/// <summary>
/// 处理单个传输(同步)
/// </summary>
private void ProcessSingleTransfer(TransferRequest request)
{
try
{
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
// 压缩数据(如果需要)
object transferData = request.Data;
if (config.enableCompression && ShouldCompress(request.Data))
{
transferData = CompressData(request.Data);
}
// 推送到Lua
bridgeCore.PushToLua(request.LuaVarName, transferData);
stopwatch.Stop();
// 记录结果
var result = new TransferResult
{
RequestId = request.RequestId,
Success = true,
TransferTimeMs = stopwatch.ElapsedMilliseconds,
DataSize = EstimateDataSize(request.Data),
CompletionTime = DateTime.Now
};
resultQueue.Enqueue(result);
// 更新统计
stats.SuccessfulTransfers++;
stats.TotalTransferTimeMs += stopwatch.ElapsedMilliseconds;
}
catch (Exception ex)
{
Debug.LogError($"传输失败: {request.RequestId} - {ex.Message}");
var result = new TransferResult
{
RequestId = request.RequestId,
Success = false,
ErrorMessage = ex.Message,
CompletionTime = DateTime.Now
};
resultQueue.Enqueue(result);
stats.FailedTransfers++;
}
}
/// <summary>
/// 异步处理单个传输
/// </summary>
private async Task ProcessSingleTransferAsync(TransferRequest request, CancellationToken cancellationToken)
{
await Task.Run(() => ProcessSingleTransfer(request), cancellationToken);
}
/// <summary>
/// 处理结果
/// </summary>
private void ProcessResults()
{
int processedCount = 0;
while (processedCount < 100 && resultQueue.TryDequeue(out TransferResult result))
{
// 这里可以处理结果,例如触发回调、更新UI等
processedCount++;
// 更新统计
if (result.Success)
{
stats.AverageTransferTimeMs =
(stats.AverageTransferTimeMs * (stats.SuccessfulTransfers - 1) + result.TransferTimeMs) /
stats.SuccessfulTransfers;
}
}
}
/// <summary>
/// 检查是否需要压缩
/// </summary>
private bool ShouldCompress(object data)
{
if (data == null)
return false;
// 估计数据大小
int estimatedSize = EstimateDataSize(data);
return estimatedSize >= config.compressionThreshold;
}
/// <summary>
/// 压缩数据
/// </summary>
private object CompressData(object data)
{
if (data == null)
return data;
// 这里可以实现数据压缩逻辑
// 简化实现:返回原始数据
return data;
}
/// <summary>
/// 估计数据大小
/// </summary>
private int EstimateDataSize(object data)
{
if (data == null)
return 0;
if (data is byte[] bytes)
return bytes.Length;
if (data is string str)
return System.Text.Encoding.UTF8.GetByteCount(str);
// 其他类型使用近似估计
return 100; // 默认100字节
}
/// <summary>
/// 更新统计信息
/// </summary>
private void UpdateStats()
{
stats.QueueSize = transferQueue.Count;
stats.ResultQueueSize = resultQueue.Count;
stats.CurrentBatchSize = currentBatch.Count;
stats.ActiveTransfers = config.useAsyncTransfer ?
config.maxConcurrentTransfers - transferSemaphore.CurrentCount : 0;
}
/// <summary>
/// 获取统计信息
/// </summary>
public TransferStats GetStats()
{
return stats;
}
/// <summary>
/// 重置统计信息
/// </summary>
public void ResetStats()
{
stats = new TransferStats();
}
/// <summary>
/// 清空队列
/// </summary>
public void ClearQueues()
{
while (transferQueue.TryDequeue(out _)) { }
while (resultQueue.TryDequeue(out _)) { }
currentBatch.Clear();
Debug.Log("传输队列已清空");
}
/// <summary>
/// 紧急传输(绕过队列)
/// </summary>
public void EmergencyTransfer(string luaVarName, object data)
{
try
{
bridgeCore.PushToLua(luaVarName, data);
stats.EmergencyTransfers++;
}
catch (Exception ex)
{
Debug.LogError($"紧急传输失败: {ex.Message}");
}
}
}
/// <summary>
/// 传输优先级
/// </summary>
public enum TransferPriority
{
Low = 0,
Normal = 1,
High = 2,
Critical = 3
}
/// <summary>
/// 传输状态
/// </summary>
public enum TransferStatus
{
Pending = 0,
Processing = 1,
Completed = 2,
Failed = 3,
Cancelled = 4
}
/// <summary>
/// 传输请求
/// </summary>
public class TransferRequest
{
public string RequestId { get; set; }
public string LuaVarName { get; set; }
public object Data { get; set; }
public TransferPriority Priority { get; set; }
public DateTime SubmitTime { get; set; }
public DateTime? StartTime { get; set; }
}
/// <summary>
/// 传输结果
/// </summary>
public class TransferResult
{
public string RequestId { get; set; }
public bool Success { get; set; }
public long TransferTimeMs { get; set; }
public int DataSize { get; set; }
public string ErrorMessage { get; set; }
public DateTime CompletionTime { get; set; }
}
/// <summary>
/// 批量传输项
/// </summary>
public class TransferBatchItem
{
public string LuaVarName { get; set; }
public object Data { get; set; }
public TransferPriority Priority { get; set; } = TransferPriority.Normal;
}
/// <summary>
/// 传输统计信息
/// </summary>
public class TransferStats
{
public int SubmittedRequests { get; set; }
public int SuccessfulTransfers { get; set; }
public int FailedTransfers { get; set; }
public int DroppedRequests { get; set; }
public int EmergencyTransfers { get; set; }
public long TotalTransferTimeMs { get; set; }
public float AverageTransferTimeMs { get; set; }
public int QueueSize { get; set; }
public int ResultQueueSize { get; set; }
public int CurrentBatchSize { get; set; }
public int ActiveTransfers { get; set; }
public int ProcessedBatches { get; set; }
public int FailedBatches { get; set; }
public long LastBatchTimeMs { get; set; }
}
/// <summary>
/// 传输队列已满异常
/// </summary>
public class TransferQueueFullException : Exception
{
public TransferQueueFullException(string message) : base(message) { }
public TransferQueueFullException(string message, Exception inner) : base(message, inner) { }
}
}
第三部分:Lua虚拟机集成与数据绑定
3.1 Lua虚拟机管理器
-- vehicle_lua_vm.lua - Lua虚拟机管理器
local VehicleLuaVM = {}
-- Lua虚拟机配置
VehicleLuaVM.config = {
memory_limit = 256 * 1024 * 1024, -- 256MB内存限制
gc_pause = 100, -- GC暂停时间
gc_step_multiplier = 200, -- GC步进乘数
instruction_limit = 1000000, -- 指令限制
enable_jit = true, -- 启用JIT编译
jit_options = {
"maxtrace=1000",
"maxrecord=4000",
"maxirconst=1000",
"maxside=100"
},
enable_debug = false, -- 启用调试
enable_profiling = true, -- 启用性能分析
max_stack_depth = 100 -- 最大调用栈深度
}
-- 虚拟机状态
VehicleLuaVM.state = {
initialized = false,
memory_usage = 0,
instruction_count = 0,
call_depth = 0,
gc_stats = {
count = 0,
pause = 0,
stepmul = 0
},
performance_stats = {
total_calls = 0,
total_time = 0,
avg_time = 0
}
}
-- 注册表(用于C#对象引用)
VehicleLuaVM.registry = {
objects = {}, -- C#对象引用
callbacks = {}, -- 回调函数
types = {}, -- 类型映射
cache = {} -- 数据缓存
}
-- 桥接函数表
VehicleLuaVM.bridge_functions = {}
-- 初始化Lua虚拟机
function VehicleLuaVM:initialize()
if self.state.initialized then
print("Lua虚拟机已初始化")
return
end
print("正在初始化Lua虚拟机...")
-- 设置内存限制
collectgarbage("setpause", self.config.memory_limit)
collectgarbage("setstepmul", self.config.gc_step_multiplier)
-- 设置JIT编译(如果可用)
if self.config.enable_jit and jit then
self:setup_jit()
end
-- 注册基础库
self:register_base_libraries()
-- 注册车机特定库
self:register_vehicle_libraries()
-- 注册C#桥接函数
self:register_bridge_functions()
-- 设置调试钩子(如果需要)
if self.config.enable_debug then
self:setup_debug_hooks()
end
-- 设置性能分析
if self.config.enable_profiling then
self:setup_profiling()
end
self.state.initialized = true
print("Lua虚拟机初始化完成")
return true
end
-- 设置JIT编译
function VehicleLuaVM:setup_jit()
if not jit then
print("警告: JIT编译不可用")
return
end
-- 设置JIT选项
for _, option in ipairs(self.config.jit_options) do
jit.opt[option] = true
end
-- 启用JIT
jit.on()
print("JIT编译已启用")
end
-- 注册基础库
function VehicleLuaVM:register_base_libraries()
-- 确保基础库已加载
local required_libs = {
"base", "coroutine", "table", "string",
"math", "io", "os", "debug", "package"
}
for _, lib in ipairs(required_libs) do
if not package.loaded[lib] then
require(lib)
end
end
print("基础库已注册")
end
-- 注册车机特定库
function VehicleLuaVM:register_vehicle_libraries()
-- 车机数据访问库
local vehicle_data = {
can = require("vehicle_can"),
sensors = require("vehicle_sensors"),
control = require("vehicle_control"),
media = require("vehicle_media"),
ui = require("vehicle_ui")
}
-- 将车机库注册到全局环境
for name, lib in pairs(vehicle_data) do
_G[name] = lib
print("已注册车机库: " .. name)
end
-- 注册车机数据类型
self:register_vehicle_data_types()
end
-- 注册车机数据类型
function VehicleLuaVM:register_vehicle_data_types()
-- CAN消息类型
_G.CanMessage = {
__name = "CanMessage",
__index = {
get_id = function(self) return self.id end,
get_data = function(self) return self.data end,
get_timestamp = function(self) return self.timestamp end,
to_string = function(self)
return string.format("CanMessage[id=0x%X, data=%s, timestamp=%d]",
self.id, string.format("%02X", table.unpack(self.data)), self.timestamp)
end
}
}
-- 车辆状态类型
_G.VehicleState = {
__name = "VehicleState",
__index = {
get_speed = function(self) return self.speed end,
get_rpm = function(self) return self.rpm end,
get_fuel_level = function(self) return self.fuel_level end,
get_engine_temp = function(self) return self.engine_temp end,
to_string = function(self)
return string.format("VehicleState[speed=%d, rpm=%d, fuel=%.1f%%, temp=%.1f°C]",
self.speed, self.rpm, self.fuel_level, self.engine_temp)
end
}
}
-- 传感器数据类型
_G.SensorData = {
__name = "SensorData",
__index = {
get_acceleration = function(self) return self.acceleration end,
get_gyro = function(self) return self.gyro end,
get_gps = function(self) return self.gps end,
to_string = function(self)
return string.format("SensorData[acc=(%.2f, %.2f, %.2f), gyro=(%.2f, %.2f, %.2f)]",
self.acceleration.x, self.acceleration.y, self.acceleration.z,
self.gyro.x, self.gyro.y, self.gyro.z)
end
}
}
print("车机数据类型已注册")
end
-- 注册桥接函数
function VehicleLuaVM:register_bridge_functions()
-- C#序列化函数
_G.csharp = _G.csharp or {}
_G.csharp.serialize = function(obj)
return self.bridge_functions.serialize(obj)
end
_G.csharp.deserialize = function(data)
return self.bridge_functions.deserialize(data)
end
-- C#对象管理函数
_G.csharp.create_object = function(type_name, ...)
return self.bridge_functions.create_object(type_name, ...)
end
_G.csharp.destroy_object = function(obj_ref)
return self.bridge_functions.destroy_object(obj_ref)
end
-- C#方法调用函数
_G.csharp.call_method = function(obj_ref, method_name, ...)
return self.bridge_functions.call_method(obj_ref, method_name, ...)
end
-- 性能监控函数
_G.csharp.get_perf_stats = function()
return self.bridge_functions.get_perf_stats()
end
-- 车机特定函数
_G.csharp.can_read = function(channel, message_id)
return self.bridge_functions.can_read(channel, message_id)
end
_G.csharp.can_write = function(channel, message_id, data)
return self.bridge_functions.can_write(channel, message_id, data)
end
print("桥接函数已注册")
end
-- 设置调试钩子
function VehicleLuaVM:setup_debug_hooks()
debug.sethook(function(event, line)
self:debug_hook(event, line)
end, "l", 1000) -- 每1000行执行一次
print("调试钩子已设置")
end
-- 调试钩子函数
function VehicleLuaVM:debug_hook(event, line)
if event == "line" then
self.state.instruction_count = self.state.instruction_count + 1
-- 检查指令限制
if self.state.instruction_count > self.config.instruction_limit then
error("指令限制超出: " .. self.config.instruction_limit)
end
elseif event == "call" then
self.state.call_depth = self.state.call_depth + 1
-- 检查调用栈深度
if self.state.call_depth > self.config.max_stack_depth then
error("调用栈深度超出: " .. self.config.max_stack_depth)
end
elseif event == "return" then
self.state.call_depth = math.max(0, self.state.call_depth - 1)
end
end
-- 设置性能分析
function VehicleLuaVM:setup_profiling()
self.profiler = {
call_times = {},
memory_samples = {},
last_sample_time = os.clock()
}
-- 设置性能采样钩子
debug.sethook(function(event)
if event == "call" then
self:profile_call_hook()
end
end, "c", 10000) -- 每10000次调用采样一次
print("性能分析已启用")
end
-- 性能分析钩子
function VehicleLuaVM:profile_call_hook()
local info = debug.getinfo(2, "nS")
if info and info.name then
local func_name = info.name or "anonymous"
if not self.profiler.call_times[func_name] then
self.profiler.call_times[func_name] = {
call_count = 0,
total_time = 0
}
end
self.profiler.call_times[func_name].call_count =
self.profiler.call_times[func_name].call_count + 1
end
end
-- 更新虚拟机状态
function VehicleLuaVM:update()
if not self.state.initialized then
return
end
-- 更新内存使用
self.state.memory_usage = collectgarbage("count") * 1024
-- 更新GC统计
self.state.gc_stats.count = collectgarbage("count")
self.state.gc_stats.pause = collectgarbage("setpause")
self.state.gc_stats.stepmul = collectgarbage("setstepmul")
-- 性能采样
self:collect_performance_samples()
-- 检查内存限制
if self.state.memory_usage > self.config.memory_limit then
print("警告: Lua内存使用超出限制 (" ..
self.state.memory_usage .. " > " .. self.config.memory_limit .. ")")
self:run_gc()
end
end
-- 收集性能样本
function VehicleLuaVM:collect_performance_samples()
local current_time = os.clock()
if current_time - self.profiler.last_sample_time >= 1.0 then -- 每秒一次
table.insert(self.profiler.memory_samples, {
time = current_time,
memory = self.state.memory_usage,
instruction_count = self.state.instruction_count
})
-- 保持最近60个样本
if #self.profiler.memory_samples > 60 then
table.remove(self.profiler.memory_samples, 1)
end
self.profiler.last_sample_time = current_time
end
end
-- 运行垃圾回收
function VehicleLuaVM:run_gc()
print("正在运行Lua垃圾回收...")
local start_memory = collectgarbage("count")
collectgarbage("collect")
local end_memory = collectgarbage("count")
local freed_memory = (start_memory - end_memory) * 1024
print(string.format("垃圾回收完成,释放了 %.2f KB 内存", freed_memory / 1024))
return freed_memory
end
-- 执行Lua代码
function VehicleLuaVM:execute(code, chunk_name)
if not self.state.initialized then
error("Lua虚拟机未初始化")
end
local start_time = os.clock()
-- 重置指令计数
self.state.instruction_count = 0
-- 执行代码
local func, err = load(code, chunk_name or "chunk", "t")
if not func then
error("Lua代码加载失败: " .. err)
end
local success, result = pcall(func)
local end_time = os.clock()
local execution_time = end_time - start_time
-- 更新性能统计
self.state.performance_stats.total_calls = self.state.performance_stats.total_calls + 1
self.state.performance_stats.total_time = self.state.performance_stats.total_time + execution_time
self.state.performance_stats.avg_time =
self.state.performance_stats.total_time / self.state.performance_stats.total_calls
if not success then
error("Lua代码执行失败: " .. result)
end
return result, execution_time
end
-- 调用Lua函数
function VehicleLuaVM:call_function(func_name, ...)
if not self.state.initialized then
error("Lua虚拟机未初始化")
end
-- 获取全局函数
local func = _G[func_name]
if type(func) ~= "function" then
error("Lua函数不存在: " .. func_name)
end
local start_time = os.clock()
-- 调用函数
local success, result = pcall(func, ...)
local end_time = os.clock()
local call_time = end_time - start_time
-- 更新性能统计
self.state.performance_stats.total_calls = self.state.performance_stats.total_calls + 1
self.state.performance_stats.total_time = self.state.performance_stats.total_time + call_time
self.state.performance_stats.avg_time =
self.state.performance_stats.total_time / self.state.performance_stats.total_calls
if not success then
error("Lua函数调用失败: " .. result)
end
return result, call_time
end
-- 注册C#对象引用
function VehicleLuaVM:register_object(obj_ref, obj)
if not obj_ref then
error("对象引用不能为空")
end
self.registry.objects[obj_ref] = obj
print("已注册C#对象引用: " .. obj_ref)
return obj_ref
end
-- 获取C#对象
function VehicleLuaVM:get_object(obj_ref)
return self.registry.objects[obj_ref]
end
-- 注销C#对象引用
function VehicleLuaVM:unregister_object(obj_ref)
if self.registry.objects[obj_ref] then
self.registry.objects[obj_ref] = nil
print("已注销C#对象引用: " .. obj_ref)
return true
end
return false
end
-- 注册回调函数
function VehicleLuaVM:register_callback(callback_name, func)
if type(func) ~= "function" then
error("回调必须是函数: " .. callback_name)
end
self.registry.callbacks[callback_name] = func
print("已注册回调函数: " .. callback_name)
return true
end
-- 调用回调函数
function VehicleLuaVM:invoke_callback(callback_name, ...)
local callback = self.registry.callbacks[callback_name]
if not callback then
error("回调函数不存在: " .. callback_name)
end
return callback(...)
end
-- 数据缓存
function VehicleLuaVM:cache_data(key, data, ttl)
self.registry.cache[key] = {
data = data,
expiry_time = ttl and (os.time() + ttl) or nil
}
return true
end
function VehicleLuaVM:get_cached_data(key)
local cached = self.registry.cache[key]
if not cached then
return nil
end
-- 检查过期时间
if cached.expiry_time and os.time() > cached.expiry_time then
self.registry.cache[key] = nil
return nil
end
return cached.data
end
-- 获取性能报告
function VehicleLuaVM:get_performance_report()
local report = {
memory_usage = self.state.memory_usage,
memory_limit = self.config.memory_limit,
instruction_count = self.state.instruction_count,
instruction_limit = self.config.instruction_limit,
call_depth = self.state.call_depth,
max_stack_depth = self.config.max_stack_depth,
gc_stats = self.state.gc_stats,
performance_stats = self.state.performance_stats,
object_count = self:count_objects(),
callback_count = self:count_callbacks(),
cache_size = self:count_cached_items()
}
-- 添加函数调用统计
report.function_stats = {}
for func_name, stats in pairs(self.profiler.call_times) do
table.insert(report.function_stats, {
name = func_name,
call_count = stats.call_count,
avg_time = stats.total_time / math.max(stats.call_count, 1)
})
end
-- 按调用次数排序
table.sort(report.function_stats, function(a, b)
return a.call_count > b.call_count
end)
return report
end
-- 统计对象数量
function VehicleLuaVM:count_objects()
local count = 0
for _ in pairs(self.registry.objects) do
count = count + 1
end
return count
end
-- 统计回调数量
function VehicleLuaVM:count_callbacks()
local count = 0
for _ in pairs(self.registry.callbacks) do
count = count + 1
end
return count
end
-- 统计缓存项数量
function VehicleLuaVM:count_cached_items()
local count = 0
for _ in pairs(self.registry.cache) do
count = count + 1
end
return count
end
-- 清理过期缓存
function VehicleLuaVM:cleanup_cache()
local removed_count = 0
local current_time = os.time()
for key, cached in pairs(self.registry.cache) do
if cached.expiry_time and current_time > cached.expiry_time then
self.registry.cache[key] = nil
removed_count = removed_count + 1
end
end
if removed_count > 0 then
print("已清理 " .. removed_count .. " 个过期缓存项")
end
return removed_count
end
-- 紧急清理
function VehicleLuaVM:emergency_cleanup()
print("执行紧急清理...")
-- 清理缓存
self.registry.cache = {}
-- 清理非必要的回调
local essential_callbacks = {}
for name, func in pairs(self.registry.callbacks) do
if name:match("^vehicle_") or name:match("^critical_") then
essential_callbacks[name] = func
end
end
self.registry.callbacks = essential_callbacks
-- 运行垃圾回收
local freed_memory = self:run_gc()
print("紧急清理完成")
return freed_memory
end
-- 关闭虚拟机
function VehicleLuaVM:shutdown()
if not self.state.initialized then
return
end
print("正在关闭Lua虚拟机...")
-- 清理所有资源
self.registry.objects = {}
self.registry.callbacks = {}
self.registry.types = {}
self.registry.cache = {}
-- 清理全局环境
self:cleanup_global_environment()
-- 运行最终垃圾回收
collectgarbage("collect")
self.state.initialized = false
print("Lua虚拟机已关闭")
end
-- 清理全局环境
function VehicleLuaVM:cleanup_global_environment()
-- 保存基础库
local protected_libs = {
"_G", "string", "table", "math", "io", "os",
"debug", "package", "coroutine", "jit"
}
local protected = {}
for _, name in ipairs(protected_libs) do
protected[name] = _G[name]
end
-- 清空全局环境
for name, value in pairs(_G) do
if not protected[name] then
_G[name] = nil
end
end
print("全局环境已清理")
end
-- 导出VehicleLuaVM
return VehicleLuaVM
更多推荐
所有评论(0)