alielie
7 天以前 e57938fbda9bff702004038f76d009422968bff5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
namespace DeviceService.Driver
{
    /// <summary>
    /// 由 DriverManager 创建并统一管理的驱动实例代理。
    ///
    /// 驱动对象本身活在驱动包的 AppDomain 中(WPF/普通类均不可跨域封送),
    /// 因此宿主拿到的是本类的透明代理:宿主调用 <see cref="Invoke"/>、
    /// <see cref="GetMethods"/>、<see cref="Release"/> 时,实际执行都发生在驱动自己的域内。
    /// </summary>
    public sealed class DriverInstance : MarshalByRefObject
    {
        private readonly DriverLoader _owner;
 
        /// <summary>实例句柄(宿主与加载器之间定位实例的唯一标识)</summary>
        public string Handle { get; }
 
        /// <summary>驱动类型的 CLR 全名</summary>
        public string TypeFullName { get; }
 
        /// <summary>注解中的"类型"(如 CAN)</summary>
        public string DriverType { get; }
 
        /// <summary>注解中的"品牌"(如 BA)</summary>
        public string Brand { get; }
 
        /// <summary>所属驱动包名(由 DriverManager 回填,仅用于展示)</summary>
        public string PackageFolder { get; set; }
 
        // 实例由 DriverManager 长期持有,无限生存期,避免远程租约到期被回收
        public override object InitializeLifetimeService() => null;
 
        internal DriverInstance(DriverLoader owner, string handle, string typeFullName,
                                string driverType, string brand)
        {
            _owner = owner;
            Handle = handle;
            TypeFullName = typeFullName;
            DriverType = driverType;
            Brand = brand;
        }
 
        /// <summary>列出该驱动类型可调用的公共方法(用于确定 methodIndex)</summary>
        public DriverMethodInfo[] GetMethods()
        {
            return _owner.GetMethods(TypeFullName);
        }
 
        /// <summary>
        /// 在该驱动实例上反射调用方法。参数为字符串形式,按目标类型自动转换,
        /// out/ref 参数的回填值会包含在结果中。
        /// </summary>
        public InvokeResult Invoke(int methodIndex, string[] rawArgs)
        {
            return _owner.InvokeOnInstance(Handle, methodIndex, rawArgs);
        }
 
        /// <summary>
        /// 直接调用(原始对象参数/返回值),供动态代理使用。
        /// 注意:参数与返回值必须可跨域封送(基元类型、string、[Serializable] DTO)。
        /// </summary>
        public InvokeDirectResult InvokeDirect(int methodIndex, object[] args)
        {
            return _owner.InvokeOnInstanceDirect(Handle, methodIndex, args);
        }
 
        /// <summary>
        /// 释放该实例(若驱动实现了 IDisposable 则调用 Dispose)。
        /// </summary>
        public void Release()
        {
            _owner.ReleaseInstance(Handle);
        }
    }
}