### Testing Python/WinRT Installation Source: https://github.com/microsoft/xlang/blob/master/src/package/pywinrt/projection/readme.md Example Python code snippet to verify the successful installation of Python/WinRT by creating and manipulating a Windows Runtime Uri object. ```python import winrt.windows.foundation as wf u = wf.Uri("https://github.com/") u2 = u.combine_uri("Microsoft/xlang/tree/master/src/tool/python") print(str(u2)) ``` -------------------------------- ### Example Output from Timed Async Operations in Shell Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Provides an example of the console output produced by the Python script when using the `timed_op` decorator with asynchronous functions. It shows the "Starting" and timing messages for the `load_model` and `load_image_file` operations. ```shell Starting load_model load_model took 0.7183248 seconds Starting load_image_file load_image_file took 0.17086919999999994 seconds ``` -------------------------------- ### Example Output of Running WinML Script (Shell) Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Shows the expected output when running the Python script, including the timing information provided by the `timed_op` decorator during the model loading process. ```Shell \samples\python\winml_tutorial>py winml_tutorial.py Starting load_model load_model took 0.7060564 seconds ``` -------------------------------- ### Installing Python/WinRT Package with pip (Shell) Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Command to install the necessary Python/WinRT package from PyPI using the pip package manager. This is the first step to enable WinML functionality in Python. ```Shell > pip install winrt ``` -------------------------------- ### WinML Pipeline Timing Output Shell Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Example shell output showing the execution time for each major step of the WinML inference pipeline when run, including model loading, image loading, binding, and evaluation. ```shell Starting load_model load_model took 0.7029269 seconds Starting load_image_file load_image_file took 0.15494339999999995 seconds Starting bind_model bind_model took 0.016178600000000043 seconds Starting evaluate_model evaluate_model took 0.022036400000000067 seconds ``` -------------------------------- ### Installing Python/WinRT via pip Source: https://github.com/microsoft/xlang/blob/master/src/package/pywinrt/projection/readme.md Command to install the Python/WinRT package from the Python Package Index using the pip package manager. ```shell pip install winrt ``` -------------------------------- ### WinML Model Classification Results Shell Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Example shell output showing the final classification results obtained after running the complete WinML inference pipeline, listing the predicted labels and their confidence scores. ```shell Starting load_model load_model took 0.7041156000000001 seconds Starting load_image_file load_image_file took 0.1883804 seconds Starting bind_model bind_model took 0.01686500000000002 seconds Starting evaluate_model evaluate_model took 0.021589099999999917 seconds tabby, tabby cat with confidence of 0.931460976600647 Egyptian cat with confidence of 0.06530658155679703 Persian cat with confidence of 0.00019303907174617052 ``` -------------------------------- ### Example Application Manifest for RegFree WinRT Source: https://github.com/microsoft/xlang/blob/master/src/UndockedRegFreeWinRT/README.md Provides an example of an application manifest file used to register activatable Windows Runtime classes (TestComponent.Class1, TestComponent.Class2, TestComponent.Class3) within a non-packaged desktop application, enabling them for RegFree WinRT activation. The manifest specifies the DLL containing the classes and their threading models. ```XML ``` -------------------------------- ### Retrieving Activation Factory with xlang_lib_get_activation_factory (C) Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md This function, implemented by a library/component, is called by the PAL to retrieve the activation factory for a given class name and interface GUID. It takes the class name, the GUID of the requested factory interface, and an output parameter for the factory pointer. ```C xlang_result __stdcall xlang_lib_get_activation_factory( xlang_string class_name, GUID const& iid, void** factory ); ``` -------------------------------- ### Getting XlangString Raw Buffer in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Provides access to the raw backing buffer and its length for a XlangString. Includes variants for U8 and U16 character types. The buffer pointer is NULL and length is 0 if the string is NULL or empty. ```C XlangResult XlangGetStringRawBufferU8( XlangString string, char const* * buffer, uint32_t* length ); XlangResult XlangGetStringRawBufferU16( XlangString string, char16_t const* * buffer, uint32_t* length ); ``` -------------------------------- ### Retrieving Activation Factory in Xlang C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Retrieves an activation factory for a specified class from the Xlang platform or another component. This is the primary function for obtaining factory interfaces to create objects. Requires the class name, the GUID of the requested factory interface, and an output parameter to receive the factory pointer. ```c xlang_result __stdcall xlang_get_activation_factory( xlang_string class_name, GUID const& iid, void** factory ); ``` -------------------------------- ### Getting XlangString Encoding in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Retrieves the encoding(s) present in a XlangString. The function returns a combination of values from the XlangStringEncoding enumeration. ```C XlangStringEncoding XlangGetStringEncoding( XlangString string ); ``` -------------------------------- ### Xlang Identifier Grammar Definition Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC01 - Type System Specification.md This grammar defines the valid structure and characters for Xlang identifiers and keywords. It specifies the rules for starting and continuation characters, referencing Unicode 3.0 character classes and specific formatting characters. Note the limitation to Unicode 3.0 and earlier characters. ```Grammar identifier-or-keyword: identifier-start-character identifier-continuation-characters* identifier-start-character: letter-character underscore (U+005F) identifier-continuation-characters: identifier-continuation-character identifier-continuation-characters identifier-continuation-character identifier-continuation-character: identifier-start-character decimal-digit-character connecting-character combining-character formatting-character letter-character: A Unicode 3.0 character of classes Lu, Ll, Lt, Lm, Lo, or Nl combining-character: A Unicode 3.0 character of classes Mn or Mc decimal-digit-character: A Unicode 3.0 character of the class Nd connecting-character: A Unicode 3.0 character of the class Pc formatting-character: Zero Width Non-Joiner (U+200C) Zero Width Joiner (U+200D) ``` -------------------------------- ### Setting Up Async Main Function with asyncio in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Defines an asynchronous main function (`async_main`) to serve as the entry point for code using `await`. It demonstrates how to run this async function from a non-async context using `asyncio.run`. Requires the `asyncio` module. ```python import asyncio async def async_main(): winml_content_path = Path.cwd() / "winml_content" model_path = winml_content_path / "SqueezeNet.onnx" model = load_model(model_path) asyncio.run(async_main()) ``` -------------------------------- ### Deploying xlang.meta.natvis Visualizer - Windows Command Prompt Source: https://github.com/microsoft/xlang/blob/master/src/readme.md This command-line script creates a symbolic link (symlink) for the xlang.meta.natvis file, placing it in the appropriate Visual Studio visualizers directory. This allows the Visual Studio debugger to display custom visualizations for xlang::meta types. It uses standard Windows command-line tools like 'reg query', 'vswhere', 'md', and 'mklink'. ```Batch for /f "tokens=2*" %i in ('reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Personal ^| findstr Personal') do @for /f "tokens=2" %k in ('"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere" -latest ^| findstr catalog_productLineVersion') do @echo %j\Visual Studio %k\Visualizers| for /f "delims=" %l in ('more') do @md "%l" 2>nul & mklink "%l\xlang.meta.natvis" "c:\git\xlang\src\library\xlang.meta.natvis" 2>nul ``` -------------------------------- ### Complete WinML Inference Pipeline Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Demonstrates the full sequence of operations for performing inference with a WinML model: loading the model and image, binding inputs, evaluating the model, loading classification labels from a file, and printing the top results. ```python async def async_main(): winml_content_path = Path.cwd() / "winml_content" model_path = winml_content_path / "SqueezeNet.onnx" model = load_model(model_path) image_file = winml_content_path / "kitten_224.png" image_frame = await load_image_file(image_file) session, binding = bind_model(model, image_frame) results = evaluate_model(session, binding) labels_path = winml_content_path / "Labels.txt" labels = load_labels(labels_path) print_results(results, labels) ``` -------------------------------- ### Calling WinML Model Loading Function in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Demonstrates how to set up the model path using `pathlib` and call the `load_model` function to load the ONNX model into memory. This is the main execution part of the script. ```Python from pathlib import Path winml_content_path = Path.cwd() / "winml_content" model_path = winml_content_path / "SqueezeNet.onnx" model = load_model(model_path) ``` -------------------------------- ### Loading WinML Model from File in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Python function `load_model` that uses the `winrt.windows.ai.machinelearning` module to load a WinML model from a specified file path. It utilizes `os.fspath` for path compatibility and is decorated with `timed_op`. ```Python import winrt.windows.ai.machinelearning as winml import os @timed_op def load_model(model_path): return winml.LearningModel.load_from_file_path(os.fspath(model_path)) ``` -------------------------------- ### Loading Image File into VideoFrame using WinRT in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Asynchronously loads an image file from a given path using WinRT APIs, decodes it with `BitmapDecoder`, and creates a `VideoFrame` from the resulting software bitmap. It demonstrates awaiting WinRT async methods like `get_file_from_path_async` and `open_async`. Requires specific WinRT modules and the `@timed_op` decorator. ```python from winrt.windows.graphics.imaging import BitmapDecoder from winrt.windows.media import VideoFrame from winrt.windows.storage import StorageFile, FileAccessMode @timed_op async def load_image_file(file_path): file = await StorageFile.get_file_from_path_async(os.fspath(file_path)) stream = await file.open_async(FileAccessMode.READ) decoder = await BitmapDecoder.create_async(stream) software_bitmap = await decoder.get_software_bitmap_async() return VideoFrame.create_with_software_bitmap(software_bitmap) ``` -------------------------------- ### Run Windows Build Script Source: https://github.com/microsoft/xlang/blob/master/src/readme.md Execute the Windows build script from a Visual Studio 2017 Developer Command Prompt. This script automates the CMake configuration and Ninja build process for the xlang project. ```shell .\src\scripts\windows\build.cmd ``` -------------------------------- ### Print Top Model Results Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Takes the model evaluation results (a vector view of confidences) and a dictionary mapping label indices to text labels. It sorts the results by confidence and prints the top 3 predictions along with their percentage confidence scores. ```python def print_results(results, labels): for confidence, label in sorted(zip(results, labels), reverse=True)[:3]: print(f"{labels[label]} ({confidence * 100:.1f}%)") ``` -------------------------------- ### Adapting Timing Decorator for Async Functions in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Replaces a standard timing decorator to correctly handle and time both synchronous and asynchronous Python functions. It uses `asyncio.iscoroutinefunction` to determine which wrapper to apply. Requires `asyncio` and `time` modules. ```python import asyncio def timed_op(fun): import time def sync_wrapper(*args, **kwds): print("Starting", fun.__name__) start = time.perf_counter() ret = fun(*args, **kwds) end = time.perf_counter() print(fun.__name__, "took", end - start, "seconds") return ret async def async_wrapper(*args, **kwds): print("Starting", fun.__name__) start = time.perf_counter() ret = await fun(*args, **kwds) end = time.perf_counter() print(fun.__name__, "took", end - start, "seconds") return ret return async_wrapper if asyncio.iscoroutinefunction(fun) else sync_wrapper ``` -------------------------------- ### Calling Async Image Loading Function in Async Main in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Updates the `async_main` function to include a call to the `load_image_file` function. It shows how to `await` the result of the async image loading operation within the main asynchronous execution flow. Requires the `load_image_file` function to be defined. ```python async def async_main(): winml_content_path = Path.cwd() / "winml_content" model_path = winml_content_path / "SqueezeNet.onnx" model = load_model(model_path) image_file = winml_content_path / "kitten_224.png" image_frame = await load_image_file(image_file) ``` -------------------------------- ### Binding WinML Model and Image Input in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md This function creates a LearningModelSession and LearningModelBinding for a given model and image frame. It binds the image frame as an ImageFeatureValue to the input named 'data_0' and prepares a TensorFloat shape for the output named 'softmaxout_1'. It returns the created session and binding. ```python @timed_op def bind_model(model, image_frame): device = winml.LearningModelDevice(winml.LearningModelDeviceKind.DEFAULT) session = winml.LearningModelSession(model, device) binding = winml.LearningModelBinding(session) image_feature_value = winml.ImageFeatureValue.create_from_video_frame(image_frame) binding.bind("data_0", image_feature_value) shape = winml.TensorFloat.create([1, 1000, 1, 1]) binding.bind("softmaxout_1", shape) return (session, binding) ``` -------------------------------- ### Evaluate WinML Model Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Evaluates the loaded WinML model using the provided session and binding. It retrieves the output tensor, converts it to a Python-compatible format using `_from`, and returns the results as a vector view for further processing. ```python @timed_op def evaluate_model(session, binding): results = session.evaluate(binding, "RunId") o = results.outputs["softmaxout_1"] result_tensor = winml.TensorFloat._from(o) return result_tensor.get_as_vector_view() ``` -------------------------------- ### Calling WinML Binding Function in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md This asynchronous function demonstrates how to integrate the bind_model function into a typical WinML workflow. It loads a model and an image, then calls bind_model, using destructuring assignment to unpack the returned session and binding objects. ```python async def async_main(): winml_content_path = Path.cwd() / "winml_content" model_path = winml_content_path / "SqueezeNet.onnx" model = load_model(model_path) image_file = winml_content_path / "kitten_224.png" image_frame = await load_image_file(image_file) session, binding = bind_model(model, image_frame) results = evaluate_model(session, binding) ``` -------------------------------- ### Defining the IUnknown COM Interface (C++) Source: https://github.com/microsoft/xlang/blob/master/design_notes/XDN05 - xlang Binary Interface.md This snippet defines the structure of the fundamental IUnknown COM interface in C++. It includes the QueryInterface method for interface navigation and AddRef/Release for reference counting, which are essential for COM object lifetime management. All COM interfaces derive from this base interface. ```C++ // IUnknown GUID identifier: 00000000-0000-0000-C000-000000000046 struct IUnknown { int32_t QueryInterface(guid const& id, void** object); uint32_t AddRef(); uint32_t Release(); }; ``` -------------------------------- ### Defining a Timing Decorator in Python Source: https://github.com/microsoft/xlang/blob/master/samples/python/winml_tutorial/readme.md Defines a Python decorator `timed_op` that measures and prints the execution time of the function it decorates. This is used to benchmark operations like model loading. ```Python def timed_op(fun): import time def wrapper(*args, **kwds): print("Starting", fun.__name__) start = time.perf_counter() ret = fun(*args, **kwds) end = time.perf_counter() print(fun.__name__, "took", end - start, "seconds") return ret return wrapper ``` -------------------------------- ### Creating Xlang String (C) Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Creates a new heap-allocated XlangString from a source string. The function copies the source string data and manages the memory internally. Use XlangDeleteString to release the string. Pass NULL for sourceString and 0 for length to create an empty or NULL string. ```C XlangResult XlangCreateStringU8( char const* sourceString, uint32_t length, XlangString* string ); XlangResult XlangCreateStringU16( char16_t const* sourceString, uint32_t length, XlangString* string ); ``` -------------------------------- ### Defining Namespace and Interface (C#) Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC02 - Metadata Representation.md This C# code snippet demonstrates how a namespace and interface are defined. Xlang encodes the full type name, such as 'Example.Foundation.ISimpleInterface', using a period-delimited string derived from these definitions. ```C# namespace Example { namespace Foundation { interface ISimpleInterface { void Method1(int paramOne); }; }; }; ``` -------------------------------- ### Creating Fast-Pass Xlang String Reference (C) Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Creates a fast-pass XlangString reference that points directly to caller-owned string data without copying or heap allocation. The caller is responsible for ensuring the source string data remains valid and unchanged for the lifetime of the XlangString. ```C XlangResult XlangCreateStringReferenceU8( char const* sourceString, uint32_t length, XlangStringHeader* header, XlangString* string ); XlangResult XlangCreateStringReferenceU16( char16_t const* sourceString, uint32_t length, XlangStringHeader* header, XlangString* string ); ``` -------------------------------- ### Promoting Mutable Buffer to Xlang String in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Converts a mutable buffer, previously allocated with XlangPreallocateStringBuffer, into an immutable XlangString. This function finalizes the string creation process. The buffer handle becomes invalid after promotion. Requires the buffer handle, a pointer to receive the new XlangString, and the actual length of the string data (excluding null terminator). ```c XlangResult XlangPromoteStringBuffer( XlangStringBuffer bufferHandle, XlangString* string, uint32_t length ); ``` -------------------------------- ### Calling Async WinRT Method in Python Source: https://github.com/microsoft/xlang/blob/master/src/package/pywinrt/projection/readme.md Demonstrates how WinRT methods returning IAsync* interfaces are projected as Python coroutines and called using the 'await' keyword within an async function. ```python import winrt.windows.devices.geolocation as wdg async def get_current_latitude(): locator = wdg.Geolocator() pos = await locator.get_geoposition_async() return pos.coordinate.latitude ``` -------------------------------- ### Defining the IXlangObject Interface and Info Category Enum (C++) Source: https://github.com/microsoft/xlang/blob/master/design_notes/XDN05 - xlang Binary Interface.md This snippet defines the XlangObjectInfoCategory enumeration and the structure for the IXlangObject interface in C++. IXlangObject derives from IUnknown and adds methods like GetObjectInfo and Equals, providing additional functionality for projected xlang types beyond basic COM capabilities. ```C++ enum XlangObjectInfoCategory { TypeName, HashCode, StringRepresentation, ObjectSize }; // IXlangObject GUID identifier to be determined struct IXlangObject { bool GetObjectInfo(XlangObjectInfoCategory info_category, void** info); bool Equals(IXlangObject* object); }; ``` -------------------------------- ### Grammar for Parameterized Type Instance Signature Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC01 - Type System Specification.md Defines the grammar used to construct the string signature for parameterized interface and delegate instances, which is then used in the UUID generation algorithm. This grammar specifies how base types, interfaces, delegates, runtime classes, structs, and enums are represented in the signature string. ```Grammar signature_octets => guid_to_octets(wrt_pinterface_namespace) string_to_utf8_octets(ptype_instance_signature) wrt_pinterface_namespace => "11f47ad5-7b73-42c0-abae-878b1e16adee" ptype_instance_signature => pinterface_instance_signature | pdelegate_instance_signature pinterface_instance_signature => "pinterface(" piid_guid ";" args ")" pdelegate_instance_signature => "pinterface(" piid_guid ";" args ")" piid_guid => guid args => arg | arg ";" args arg => type_signature type_signature => base_type_identifer | com_interface_signature | interface_signature | delegate_signature | runtime_class_signature | struct_signature | enum_signature | pinterface_instance_signature | pdelegate_instance_signature com_interface_signature => "cinterface(IInspectable)" base_type_identifier is defined bellow interface_signature => guid rtime_class_signature => "rc(" runtime_class_name ";" default_interface ")" default_interface => type_signature struct_signature => "struct(" struct_name ";" args ")" enum_signature => "enum(" enum_name ";" enum_underlying_type ")" enum_underlying_type => type_signature delegate_signature => "delegate(" guid ")" guid => "{" dashed_hex "}" dashed_hex is the format uuidgen writes in when passed no arguments: dashed_hex => hex{8} "-" hex{4} "-" hex{4} "-" hex{4} "-" hex{12} hex => [0-9a-f] ``` -------------------------------- ### Defining the IXlangErrorInfo Interface in C++ Source: https://github.com/microsoft/xlang/blob/master/design_notes/XDN11 - Error handling.md This C++ snippet defines the `IXlangErrorInfo` interface used by xlang projections to expose detailed error information. It includes methods for retrieving the error code, message, language-specific error details, execution trace, projection identifier, language-specific information, and propagated errors, as well as a method for propagating errors. ```cpp struct IXLangErrorInfo { void GetError(xlang_result* error); void GetMessage(xlang_string* message); void GetLanguageError(xlang_string* error); void GetExecutionTrace(IUnknown** executionTrace); void GetProjectionIdentifier(xlang_string* identifier); void GetLanguageInformation(IUnknown** languageInformation); void GetPropagatedError(IXlangErrorInfo** propagatedError); void PropagateError( xlang_string projectionIdentifier, xlang_string languageError, IUnknown* executionTrace, IUnknown* languageInformation); } ``` -------------------------------- ### Allocating Mutable String Buffer in Xlang C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Allocates a mutable character buffer for creating Xlang strings. Use this buffer to populate string data before promoting it to an immutable XlangString using XlangPromoteStringBuffer. The buffer includes a null terminator. Requires specifying the desired length and provides pointers to the buffer and a handle. ```c XlangResult XlangPreallocateStringBufferU8( uint32_t length, char** charBuffer, XlangStringBuffer* bufferHandle ); XlangResult XlangPreallocateStringBufferU16( uint32_t length, char16_t** charBuffer, XlangStringBuffer* bufferHandle ); ``` -------------------------------- ### Duplicating XlangString in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Creates a copy of the specified string. For strings created by XlangCreateString, the reference count is incremented. For fast-pass strings created by XlangCreateStringReference, a new buffer is allocated and copied. Each call must be matched with XlangDeleteString. ```C XlangResult XlangDuplicateString( XlangString string, XlangString* newString ); ``` -------------------------------- ### Defining xlang Weak Reference Interfaces (C++) Source: https://github.com/microsoft/xlang/blob/master/design_notes/XDN05 - xlang Binary Interface.md Defines the C++ structures for the IWeakReference and IWeakReferenceSource ABI interfaces. These interfaces are used internally by xlang to manage weak references, allowing objects to be collected even if weak references exist, thus preventing circular reference issues. Both interfaces inherit from IUnknown. ```cpp // IWeakReference GUID identifier: 00000037-0000-0000-C000-000000000046 struct IWeakReference : IUnknown { int32_t Resolve(guid const& iid, void** object_reference); }; // IWeakReferenceSource GUID identifier: 00000038-0000-0000-C000-000000000046 struct IWeakReferenceSource : IUnknown { int32_t GetWeakReference(IWeakReference** weak_reference); }; ``` -------------------------------- ### Creating a TensorFloat Shape in Python Source: https://github.com/microsoft/xlang/blob/master/src/package/pywinrt/projection/readme.md This snippet demonstrates creating a Windows.AI.MachineLearning.TensorFloat object with a specified shape using a Python list. Python/WinRT automatically converts the Python list into the required WinRT collection type (IIterable) for the create method. ```python shape = winml.TensorFloat.create([1, 1000, 1, 1]) ``` -------------------------------- ### Discarding XlangStringBuffer in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Discards a preallocated string buffer if it was not promoted to a XlangString. Call this function to discard a buffer created by XlangPreallocateStringBuffer that hasn't been promoted by XlangPromoteStringBuffer. Calling XlangPromoteStringBuffer after this is undefined. ```C XlangResult XlangDeleteStringBuffer( XlangStringBuffer bufferHandle ); ``` -------------------------------- ### Function Signature for Error Indication in xlang ABI (C++) Source: https://github.com/microsoft/xlang/blob/master/design_notes/XDN11 - Error handling.md This snippet shows the recommended function signature for xlang ABI functions that need to indicate errors. The function returns an `IXlangErrorInfo*` pointer. A return value of `nullptr` (or 0) indicates success, while a non-`nullptr` value indicates an error and represents the error information object. The `[[nodiscard]]` attribute is used to warn callers if they ignore the return value, emphasizing that the caller takes ownership of the returned error object on failure. ```cpp [[nodiscard]] IXlangErrorInfo* functionName(param, ...) ``` -------------------------------- ### Propagating an existing xlang error (C++) Source: https://github.com/microsoft/xlang/blob/master/design_notes/XDN11 - Error handling.md This method, part of the IXlangErrorInfo interface, is used to add language-specific diagnostic information to an existing xlang error info object when an error is a propagation of a previous xlang error. This helps preserve the original error identity while adding context. ```C++ void PropagateError( xlang_string projectionIdentifier, xlang_string languageError, IUnknown* executionTrace, IUnknown* languageInformation) ``` -------------------------------- ### Python Projection of WinRT Enum Source: https://github.com/microsoft/xlang/blob/master/src/package/pywinrt/projection/readme.md Illustrates how a Windows Runtime enum like PositionStatus is projected as a Python IntEnum with members in UPPER_SNAKE_CASE. ```python class PositionStatus(enum.IntEnum): READY = 0 INITIALIZING = 1 NO_DATA = 2 DISABLED = 3 NOT_INITIALIZED = 4 NOT_AVAILABLE = 5 ``` -------------------------------- ### Defining XlangStringBuffer Type in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Defines the XlangStringBuffer type, used to hold a preallocated string buffer for subsequent promotion to a XlangString. It is the size of a pointer but distinct. ```C typedef struct XlangStringBuffer__ { int unused; } XlangStringBuffer__; typedef XlangStringBuffer__* XlangStringBuffer; ``` -------------------------------- ### Allocating Shared Memory with XlangMemAlloc in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Allocates a block of memory intended for sharing between in-process components using different allocators. The memory must be freed using XlangMemFree. It is thread-safe. ```C void* __stdcall XlangMemAlloc(size_t count); ``` -------------------------------- ### Defining the XlangString Opaque Handle Type in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC04 - Application Binary Interface.md This C code defines an opaque handle type `XlangString` used to represent strings in the Xlang ABI. It's defined as a pointer to an incomplete struct, ensuring the internal structure is hidden and treated as a distinct pointer type. ```C typedef struct XlangString__ { int unused; } XlangString__; typedef XlangString__* XlangString; ``` -------------------------------- ### Freeing Shared Memory with XlangMemFree in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Frees a block of memory previously allocated by XlangMemAlloc. If the pointer is NULL, the function has no effect. It is thread-safe. ```C void __stdcall XlangMemFree(void* ptr); ``` -------------------------------- ### Deleting XlangString in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Deletes a XlangString. If the string is a fast-pass string created by XlangCreateStringReference or NULL, no action is taken. This function decrements the reference count of the backing buffer and deallocates it if the count reaches 0. ```C void XlangDeleteString(XlangString string); ``` -------------------------------- ### Defining XlangStringEncoding Enum in C Source: https://github.com/microsoft/xlang/blob/master/docs/xplatwinrt/XSPEC03 - Platform Abstraction Layer.md Defines an enum representing possible character encodings (UTF-8, UTF-16) for XlangString. It is a flags enum with an unsigned 32-bit integer underlying type. ```C enum XlangStringEncoding { ENCODING_UTF8 = 0x1, ENCODING_UTF16 = 0x2 }; ``` -------------------------------- ### Originating a new xlang error (C++) Source: https://github.com/microsoft/xlang/blob/master/design_notes/XDN11 - Error handling.md This function is used by a projection to create a new xlang error info object when a language-specific error occurs that is not a propagation of a previous xlang error. It translates the language error to an xlang_result and includes diagnostic information. ```C++ [[nodiscard]] IXlangErrorInfo* xlang_originate_error( xlang_result error, xlang_string message, xlang_string projectionIdentifier, xlang_string languageError, IUnknown* executionTrace, IUnknown* languageInformation) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.