基础知识:如下所示:
1.WinRT组件使用由ECMA协会标准化的.NET元数据格式(ECMA-335)来描述其API,这些元数据会嵌入到扩展名为.winmd的文件中。
2.RCW(运行时可调用包装器)内部引用了WinRT组件。
3.CCW(COM可调用包装器)内部引用了CLR对象。

CLR投射:CLR通过元数据将WinRT类型隐式投射成FCL类型。

框架投射:CLR通过代码将WinRT类型显式投射成FCL类型。具有以下特性:
1.可以使用WindowsRuntimeSystemExtensions类中的辅助函数来完成.NET异步调用WinRT。
2.可以使用WindowsRuntimeStorageExtensions和WindowsRuntimeStreamExtensions类中的辅助函数来完成.NET和WinRT之间互传输数据流。
3.可以使用WindowsRuntimeBufferExtensions类中的辅助函数来完成.NET和WinRT之间传输数据块。

用C#定义WinRT组件:具有以下特性:
1.使用该WinRT组件时,一般会造成的额外性能损失和内存消耗。
2.使用ildasm的/project命令开关可以查看将WinRT类型投射成FCL等价类型之后的元数据。
3.C#实现WinRT组件的模板如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Metadata;// The namespace MUST match the assembly name and cannot be "Windows"
namespace LearnCLR.WinRTComponents {// [Flags]  // Must not be present if enum is int; required if enum is uintpublic enum WinRTEnum : int {    // Enums must be backed by int or uintNone,NotNone}// Structures can only contain core data types, String, & other structures// No constructors or methods are allowedpublic struct WinRTStruct {public Int32 ANumber;public String AString;public WinRTEnum AEnum;    // Really just a 32-bit integer}// Delegates must have WinRT-compatible types in the signature (no BeginInvoke/EndInvoke)public delegate String WinRTDelegate(Int32 x);// Interfaces can have methods, properties, & events but cannot be generic.public interface IWinRTInterface {// Nullable<T> marshals as IReference<T>Int32? InterfaceProperty { get; set; }}// Members without a [Version(#)] attribute default to the class's // version (1) and are part of the same underlying COM interface// produced by WinMDExp.exe.[Version(1)]// Class must be derived from Object, sealed, not generic, // implement only WinRT interfaces, & public members must be WinRT typespublic sealed class WinRTClass : IWinRTInterface {// Public fields are not allowed #region Class can expose static methods, properties, and eventspublic static String StaticMethod(String s) { return "Returning " + s; }public static WinRTStruct StaticProperty { get; set; }// In JavaScript 'out' parameters are returned as objects with each // parameter becoming a property along with the return valuepublic static String OutParameters(out WinRTStruct x, out Int32 year) {x = new WinRTStruct { AEnum = WinRTEnum.NotNone, ANumber = 333, AString = "Jeff" };year = DateTimeOffset.Now.Year;return "Grant";}#endregion// Constructor can take arguments but not out/ref argumentspublic WinRTClass(Int32? number) { InterfaceProperty = number; }public Int32? InterfaceProperty { get; set; }// Only ToString is allowed to be overriddenpublic override String ToString() {return String.Format("InterfaceProperty={0}",InterfaceProperty.HasValue ? InterfaceProperty.Value.ToString() : "(not set)");}public void ThrowingMethod() {throw new InvalidOperationException("My exception message");// To throw a specific HRESULT, use COMException instead//const Int32 COR_E_INVALIDOPERATION = unchecked((Int32)0x80131509);//throw new COMException("Invalid Operation", COR_E_INVALIDOPERATION);}#region Arrays are passed, returned OR filled; never a combinationpublic Int32 PassArray([ReadOnlyArray] /* [In] implied */ Int32[] data) {// NOTE: Modified array contents MAY not be marshaled out; do not modify the arrayreturn data.Sum();}public Int32 FillArray([WriteOnlyArray] /* [Out] implied */ Int32[] data) {// NOTE: Original array contents MAY not be marshaled in; // write to the array before reading from itfor (Int32 n = 0; n < data.Length; n++) data[n] = n;return data.Length;}public Int32[] ReturnArray() {// Array is marshaled out upon returnreturn new Int32[] { 1, 2, 3 };}#endregion// Collections are passed by referencepublic void PassAndModifyCollection(IDictionary<String, Object> collection) {collection["Key2"] = "Value2";  // Modifies collection in place via interop}#region Method overloading// Overloads with same # of parameters are considered identical to JavaScriptpublic void SomeMethod(Int32 x) { }[Windows.Foundation.Metadata.DefaultOverload]  // Attribute makes this method the default overloadpublic void SomeMethod(String s) { }#endregion#region Automatically implemented eventpublic event WinRTDelegate AutoEvent;public String RaiseAutoEvent(Int32 number) {WinRTDelegate d = AutoEvent;return (d == null) ? "No callbacks registered" : d(number);}#endregion#region Manually implemented event// Private field that keeps track of the event's registered delegatesprivate EventRegistrationTokenTable<WinRTDelegate> m_manualEvent = null;// Manual implementation of the event's add and remove methodspublic event WinRTDelegate ManualEvent {add {// Gets the existing table, or creates a new one if the table is not yet initializedreturn EventRegistrationTokenTable<WinRTDelegate>.GetOrCreateEventRegistrationTokenTable(ref m_manualEvent).AddEventHandler(value);}remove {EventRegistrationTokenTable<WinRTDelegate>.GetOrCreateEventRegistrationTokenTable(ref m_manualEvent).RemoveEventHandler(value);}}public String RaiseManualEvent(Int32 number) {WinRTDelegate d = EventRegistrationTokenTable<WinRTDelegate>.GetOrCreateEventRegistrationTokenTable(ref m_manualEvent).InvocationList;return (d == null) ? "No callbacks registered" : d(number);}#endregion#region Asynchronous methods// Async methods MUST return IAsync[Action|Operation](WithProgress)// NOTE: Other languages see the DataTimeOffset as Windows.Foundation.DateTimepublic IAsyncOperationWithProgress<DateTimeOffset, Int32> DoSomethingAsync() {// Use the System.Runtime.InteropServices.WindowsRuntime.AsyncInfo's Run methods to // invoke a private method written entirely in managed codereturn AsyncInfo.Run<DateTimeOffset, Int32>(DoSomethingAsyncInternal);}// Implement the async operation via a private method using normal .NET technologiesprivate async Task<DateTimeOffset> DoSomethingAsyncInternal(CancellationToken ct, IProgress<Int32> progress) {for (Int32 x = 0; x < 10; x++) {// This code supports cancellation and progress reportingct.ThrowIfCancellationRequested();if (progress != null) progress.Report(x * 10);await Task.Delay(1000); // Simulate doing something asynchronously}return DateTimeOffset.Now; // Ultimate return value}public IAsyncOperation<DateTimeOffset> DoSomethingAsync2() {// If you don't need cancellation & progress, use // System.WindowsRuntimeSystemExtensions' AsAsync[Action|Operation] Task // extension methods (these call AsyncInfo.Run internally)return DoSomethingAsyncInternal(default(CancellationToken), null).AsAsyncOperation();}#endregion// After you ship a version, mark new members with a [Version(#)] attribute// so that WinMDExp.exe puts the new members in a different underlying COM // interface. This is required since COM interfaces are supposed to be immutable.[Version(2)]public void NewMethodAddedInV2() { }}
}

CLR via C#:与WinRT组件互操作相关推荐

  1. 【windows8开发】C++开发WinRT组件和JS调用

    通过Windows Runtime(以下简称WinRT),可以用C++或C#或VB很方便的开发组件(dll),并且这些组件在用Javascript开发的Metro app中可以几乎无缝的被(javas ...

  2. Unity3D之调用WinRT组件

    结论 目前如果想调用WinRT组件引入原生UWP APIs,还是要切换至Universal Windows Platform平台进行调用,在目前版本的Unity(2018.1)的Standalone平 ...

  3. 【Windows8开发】关于WinRT组件,WinRT dll,Win32 dll,WinRT exe组件的一些尝试

    随着Win8的推出,提出了很多新的概念,比如WinRT Component,WinRT dll,WinRT exe component等.基于这些新的概念,进行了很多尝试,本文会把结果分享给大家,希望 ...

  4. 开发WinRT自定义组件之富文本框

    富文本框是常用的组件之一,多用于文章排版.用户评论等. WinRT组件中内置了两个:RichEditBox.RichTextBlock.RichEditBox可以编辑,RichTextBlock只用来 ...

  5. windows RT开发笔记:WinRT DLL及其调用研究

    一. 几个概念: WinRT : Windows Runtime, windows运行时.创建Windows运行时(WinRT)是为了在Windows上给用户提供一种流畅且安全的应用体验.WinRT会 ...

  6. Win10系列:VC++调用自定义组件1

    通过20.9.1小节中的代码和步骤编写了一个名为"FilePickerComponent"的WinRT组件,接下来将在上一小节所新建的项目基础上,继续介绍如何在不同的语言所编写的应 ...

  7. CLR基础,CLR运行过程,使用dos命令创建、编译、运行C#文件,查看IL代码

    CLR是Common Language Runtime的缩写,是.NET程序集或可执行程序运行的一个虚拟环境.CLR用于管理托管代码,但是它本身是由非托管代码编写的,并不是一个包含了托管代码的程序集, ...

  8. Rust/WinRT更名,全面支持Windows API

    击"开发者技术前线",选择"星标" 让一部分开发者看到未来 文 | 白开水 来自 | OSC开源社区 微软已宣布推出 Rust for Windows v0.9 ...

  9. 【Rust日报】2020-06-08 - Rust/WinRT快速入门

    mlua v0.4 发布并支持Lua 5.4 mlua v0.4 released with Lua 5.4 support https://github.com/khvzak/mlua mlua v ...

最新文章

  1. Oracle Database 11.2.0.4.0 已在 中标麒麟Linux x86-64 NeoKylin Linux Advanced Server 6 上通过认证...
  2. 字符串面试题(一)字符串逆序
  3. R 语言柱状图示例笔记
  4. 部署App-V Client,应用程序虚拟化体验系列之三
  5. 远程拷贝 linux服务器,linux scp 服务器远程拷贝(示例代码)
  6. 华为云副总裁薛浩:云原生视频服务,重塑体验,助力产业升级
  7. 无码系列-2-代码架构空想
  8. 计算机电池功能,蓄电池检测仪的主要功能都有哪些
  9. Android 应用的启动方式
  10. 刷题记录 CF每日一题打卡 2020.6月7-6月13
  11. 编码(decode与encode)
  12. 政策评估计量经济学模型(DID)
  13. AI人工智能、机器学习 面试题(2022最新版)
  14. 使用Resnet网络对人脸图像分类识别出男女性别(包含数据集制作+训练+测试)
  15. 研究生的压力应对与心理健康 测试题答案
  16. USB转串口芯片CH340G的使用,3.3V或5V供电电路
  17. 这款App连夜被下架!
  18. Hi,运维,你懂Java吗-No.2:JDK介绍及安装
  19. 融跃财经:四大会计事务所或将逐渐扩招,你准备好了没有!
  20. 在线客服系统前端多国语言实现方案和代码

热门文章

  1. headfirst 笔记 第七章
  2. 用CSS实现阴阳八卦图等图形
  3. 动态3D特效壁纸软件Wallpaper Engine的免费获取及安装问题解决
  4. 基于verilog的 PRBS编码
  5. 过了面试入职被排挤,离职是最坏的做法!
  6. 从语言之争到年龄焦虑
  7. IDEA Maven遇到的问题 wating for maven import completionomitted for duplicate jar
  8. [python]os库与shutil库与操作系统的交互-整理硬盘中Vivaldi的作品
  9. python可以在手机上学吗_Python 读书
  10. 【JS】【19】使用Jquery判断是电脑或手机或微信浏览器访问