### Download and Configure winmd Library Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt This section handles the external winmd library. If no external include directory is specified, it's downloaded using ExternalProject. CMake commands for configuration, build, and install are intentionally left empty as the library is header-only. ```cmake include(ExternalProject) ExternalProject_Add(winmd GIT_REPOSITORY https://github.com/microsoft/winmd.git GIT_TAG 0f1eae3bfa63fa2ba3c2912cbfe72a01db94cc5a CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" UPDATE_COMMAND "" ) add_dependencies(cppwinrt winmd) ExternalProject_Get_Property(winmd SOURCE_DIR) set(winmd_INCLUDE_DIR "${SOURCE_DIR}/src") ``` -------------------------------- ### Install cppwinrt Target Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Installs the cppwinrt executable target. ```cmake install(TARGETS cppwinrt) ``` -------------------------------- ### Setup CTest and Subdirectory Tests Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt This block conditionally includes CTest and adds the 'test' subdirectory for testing purposes when building on Windows, not cross-compiling, and when testing is enabled. ```cmake include(CTest) if(BUILD_TESTING) add_subdirectory(test) endif() ``` -------------------------------- ### Build Everything (Projection + Tests) Source: https://context7.com/microsoft/cppwinrt/llms.txt Use this script for the simplest, most comprehensive build of the projection and all tests. ```cmd build_test_all.cmd ``` -------------------------------- ### Enable Fast ABI for Performance Source: https://context7.com/microsoft/cppwinrt/llms.txt Generates projection headers with Fast ABI vtable support enabled for performance-critical components. ```cmd REM ── Enable Fast ABI for performance-critical components ────────────────── cppwinrt.exe -in MyFastComponent.winmd -ref sdk -out .\generated -fastabi ``` -------------------------------- ### Build Projection Headers Source: https://context7.com/microsoft/cppwinrt/llms.txt Builds only the projection headers. Output is located in _build\winrt\. ```cmd build_projection.cmd ``` -------------------------------- ### Build NuGet Package Source: https://context7.com/microsoft/cppwinrt/llms.txt Generates the NuGet package. Requires 'nuget.exe' to be available in the system's PATH. ```cmd build_nuget.cmd 3.0.240101.1 ``` -------------------------------- ### Prepare for Versionless Diffs Source: https://context7.com/microsoft/cppwinrt/llms.txt Strips version stamps from build artifacts to facilitate diffing and show only semantic changes. After running this, compare \'_build\x64\Release\winrt\' with \'_reference\x64\Release\winrt\'. ```cmd prepare_versionless_diffs.cmd ``` -------------------------------- ### Build Prior Release Projection Source: https://context7.com/microsoft/cppwinrt/llms.txt Builds the projection from a prior release, useful for comparison purposes. ```cmd build_prior_projection.cmd ``` -------------------------------- ### Build C++/WinRT NuGet Package Source: https://github.com/microsoft/cppwinrt/blob/master/nuget/readme.md Build the C++/WinRT NuGet package by running the provided script with a high version number. Ensure nuget.exe is in your PATH. ```batch c:\repos\cppwinrt> .\build_nuget.cmd 5.0.0.0 ``` -------------------------------- ### Generate Projection Headers from Windows SDK Source: https://context7.com/microsoft/cppwinrt/llms.txt Generates projection headers for the current Windows SDK to a specified output directory. ```cmd REM ── Generate projection headers from the current Windows SDK ────────────── cppwinrt.exe -in sdk -out .\generated ``` -------------------------------- ### Run All Tests Source: https://context7.com/microsoft/cppwinrt/llms.txt Executes all tests after building the necessary test binaries. ```cmd run_tests.cmd ``` -------------------------------- ### Generate with Explicit SDK Version and Verbose Output Source: https://context7.com/microsoft/cppwinrt/llms.txt Generates projection headers using a specific SDK version and enables verbose output for detailed progress information. ```cmd REM ── Generate with explicit SDK version and extensions ───────────────────── cppwinrt.exe -in 10.0.19041.0+ -out .\generated -verbose ``` -------------------------------- ### Add Windows Manifest Resources Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt For Windows builds, this custom command copies the app.manifest file and generates an app.manifest.rc file. This ensures the manifest is included in the executable. ```cmake if(WIN32) add_custom_command( OUTPUT "${PROJECT_BINARY_DIR}/app.manifest" COMMAND ${CMAKE_COMMAND} -E copy "${PROJECT_SOURCE_DIR}/cppwinrt/app.manifest" "${PROJECT_BINARY_DIR}/app.manifest" DEPENDS "${PROJECT_SOURCE_DIR}/cppwinrt/app.manifest" VERBATIM ) # Do the configure_file dance so that app.manifest.rc don't get modified every # single time the project is reconfigured and trigger a rebuild. file(WRITE "${PROJECT_BINARY_DIR}/app.manifest.rc.in" "1 24 \"app.manifest\"\n") configure_file( "${PROJECT_BINARY_DIR}/app.manifest.rc.in" "${PROJECT_BINARY_DIR}/app.manifest.rc" COPYONLY ) set(CPPWINRT_RESOURCES "${PROJECT_BINARY_DIR}/app.manifest" "${PROJECT_BINARY_DIR}/app.manifest.rc" "${PROJECT_BINARY_DIR}/version.rc" ) endif() ``` -------------------------------- ### Build Commands for CppWinRT Source: https://context7.com/microsoft/cppwinrt/llms.txt Use MSBuild to build your project with specific CppWinRT verbosity settings, or use a build script to generate a local NuGet package for testing. ```cmd REM Build with high CppWinRT verbosity at minimal MSBuild verbosity: msbuild MyApp.vcxproj /verbosity:minimal /property:CppWinRTVerbosity=high REM Build the NuGet package locally for testing: .\build_nuget.cmd 5.0.0.0 REM Then add the repo root as a NuGet source and update project references. ``` -------------------------------- ### Implement InitializeComponent for Non-Xaml Objects Source: https://github.com/microsoft/cppwinrt/blob/master/nuget/readme.md A non-Xaml object can participate in two-phase construction by defining its own InitializeComponent method to execute initialization logic that might throw exceptions. ```cpp void MyComponent::InitializeComponent() { // Execute initialization logic that may throw } ``` -------------------------------- ### Include/Exclude Specific Namespaces Source: https://context7.com/microsoft/cppwinrt/llms.txt Generates projection headers from the SDK, including only specified namespaces and excluding others. ```cmd REM ── Include only specific namespaces, exclude others ───────────────────── cppwinrt.exe ^ -in sdk ^ -out .\generated ^ -include Windows.Storage ^ -include Windows.Networking ^ -exclude Windows.Devices ``` -------------------------------- ### Build VSIX Visual Studio Extension Source: https://context7.com/microsoft/cppwinrt/llms.txt Builds the VSIX extension for Visual Studio. ```cmd build_vsix.cmd ``` -------------------------------- ### Configure C++ Standard Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Sets the C++ standard to C++17 and marks it as required. ```cmake set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED True) ``` -------------------------------- ### Using `writer` for C++ Code Generation Source: https://context7.com/microsoft/cppwinrt/llms.txt The `writer` class provides buffered output for generating C++ code. Use `write()` for placeholder formatting, `write_temp()` for temporary strings, `write_printf()` for printf-style formatting, and `write_code()` for verbatim output. It supports RAII-based indentation and can flush to files or the console, only writing if content has changed. ```cpp #include "text_writer.h" // writer is the concrete type used throughout the codebase cppwinrt::writer w; // write() uses %-as-placeholder formatting (not printf format strings) w.write("namespace % {\n", "MyNamespace"); // write_temp() writes to a temporary buffer and returns a std::string // without permanently appending to the writer std::string decl = w.write_temp(" % %;\n", "int", "value"); w.write(decl); // now permanently emit it // write_printf() for printf-style formatting w.write_printf(" %-20s%s\n", "-verbose", "Show detailed progress"); // write_code() emits source code verbatim (no placeholder processing) w.write_code("// auto-generated — do not edit\n"); // Flush to file — only writes if content differs from the existing file // (avoids unnecessarily invalidating incremental build timestamps) w.flush_to_file("winrt/Windows.Foundation.h"); // Flush to console (stdout on success, stderr on failure) w.flush_to_console(/*success=*/true); // Indentation helper { auto indent = w.push_indent({ 4 }); // RAII: adds 4-space indent w.write("indented content\n"); } // indent popped here automatically // Generic param stack for template instantiation tracking // (used internally when generating generic type projections) { auto guard = w.push_generic_params(type_spec.GenericTypeInst()); w.write("%", some_generic_type); // generic params substituted via stack } ``` -------------------------------- ### Configure Prebuild Generator Tool Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Includes the ExternalProject module to download and build the cppwinrt-prebuild tool if cross-compiling. Otherwise, it adds the prebuild subdirectory. ```cmake if(CMAKE_CROSSCOMPILING) include(ExternalProject) ExternalProject_Add(cppwinrt-prebuild SOURCE_DIR "${PROJECT_SOURCE_DIR}/prebuild" CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= "-DCPPWINRT_BUILD_VERSION=${CPPWINRT_BUILD_VERSION}" ) ExternalProject_Get_Property(cppwinrt-prebuild INSTALL_DIR) set(PREBUILD_TOOL "${INSTALL_DIR}/bin/cppwinrt-prebuild") unset(INSTALL_DIR) else() add_subdirectory(prebuild) set(PREBUILD_TOOL cppwinrt-prebuild) endif() ``` -------------------------------- ### Generate Headers and Component Skeleton for Custom WinMD Source: https://context7.com/microsoft/cppwinrt/llms.txt Generates projection headers and component skeleton files for a custom WinMD file, referencing the SDK. Includes verbose output and precompiled header settings. ```cmd REM ── Generate projection headers + component skeleton for a custom WinMD ── cppwinrt.exe ^ -in MyComponent.winmd ^ -ref sdk ^ -out .\generated ^ -component .\sources ^ -name MyComponent ^ -pch pch.h ^ -prefix ^ -verbose ``` -------------------------------- ### Check for xmllite Library and Generate Import Lib if Needed Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt This section handles a known issue with older mingw-w64 versions that lack the import library for xmllite. It tests if linking against xmllite works and generates the import library if it's missing. ```cmake # HACK: Handle the xmllite import lib. # mingw-w64 before commit 5ac1a2c is missing the import lib for xmllite. This # checks whether the current build environment provides libxmllite.a, and # generates the import lib if needed. set(XMLLITE_LIBRARY xmllite) if(MINGW) function(TestLinkXmlLite OUTPUT_VARNAME) include(CheckCXXSourceCompiles) set(CMAKE_REQUIRED_LIBRARIES xmllite) check_cxx_source_compiles(" #include int main() { CreateXmlReader(__uuidof(IXmlReader), nullptr, nullptr); } " ${OUTPUT_VARNAME}) endfunction() function(TestIsI386 OUTPUT_VARNAME) include(CheckCXXSourceCompiles) check_cxx_source_compiles(" #if !defined(__i386__) && !defined(_M_IX86) ``` -------------------------------- ### Define cppwinrt Executable Sources and Headers Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Lists the source files and header files for the cppwinrt executable. Includes autogenerated files and standard headers. ```cmake set(CPPWINRT_SRCS cppwinrt/main.cpp "${PROJECT_BINARY_DIR}/strings.cpp" ) set(CPPWINRT_HEADERS cppwinrt/pch.h cppwinrt/cmd_reader.h cppwinrt/code_writers.h cppwinrt/component_writers.h cppwinrt/file_writers.h cppwinrt/helpers.h cppwinrt/pch.h cppwinrt/settings.h cppwinrt/task_group.h cppwinrt/text_writer.h cppwinrt/type_writers.h ) ``` -------------------------------- ### Safe Xaml Initialization in C++/WinRT Source: https://context7.com/microsoft/cppwinrt/llms.txt Implement the two-phase construction pattern for Xaml pages by overriding `InitializeComponent` in your C++/WinRT implementation class. Ensure `InitializeComponent` is called after the base class constructor and before accessing Xaml properties. ```cpp // pch.h #include #include // MainPage.h — generated by cppwinrt.exe #include "MainPage.g.h" // MainPage.cpp amespace winrt::MyApp::implementation { // ── DO NOT call InitializeComponent() from the constructor ────────── MainPage::MainPage() { // InitializeComponent() is called automatically after this returns. // Accessing Xaml properties here would crash. } // ── Override InitializeComponent() to access Xaml properties safely ─ void MainPage::InitializeComponent() { // 1. Register with the Xaml runtime first (required) MainPageT::InitializeComponent(); // 2. Now Xaml properties are safe to access MyButton().Content(winrt::box_value(L"Click me")); MyTextBox().PlaceholderText(L"Enter text here"); } } // ── For classes that DERIVE from a composable base that also has Xaml ──── // Use ComponentConnectorT to correctly dispatch IComponentConnector callbacks // to the most-derived implementation: #include "DerivedPage.g.h" namespace winrt::MyApp::implementation { struct DerivedPage : DerivedPageT, winrt::Windows::UI::Xaml::Markup::ComponentConnectorT> // Correctly inherit from ComponentConnectorT { void InitializeComponent() { // Must call ComponentConnectorT::InitializeComponent(), NOT DerivedPageT:: ComponentConnectorT::InitializeComponent(); // Now both base and derived Xaml properties are accessible MyBaseButton().Content(winrt::box_value(L"Base button")); MyDerivedSlider().Value(0.5); } }; } // ── Non-Xaml two-phase construction ───────────────────────────────────── struct MyComponent : winrt::implements { void InitializeComponent() { // Called automatically after construction. // Safe place for initialization that may throw. m_resource = open_some_resource(); // exceptions handled gracefully } private: SomeResource m_resource; }; ``` -------------------------------- ### Use Response File for Long Command Lines Source: https://context7.com/microsoft/cppwinrt/llms.txt Utilizes a response file to manage arguments for cppwinrt.exe, useful for avoiding excessively long command lines. ```cmd REM ── Use a response file to avoid long command lines ─────────────────────── REM args.rsp contains: REM -in sdk REM -out .\generated REM -component .\sources cppwinrt.exe @args.rsp ``` -------------------------------- ### Link Libraries for Windows Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt On Windows, links the cppwinrt executable against the shlwapi library. ```cmake if(WIN32) target_link_libraries(cppwinrt shlwapi) endif() ``` -------------------------------- ### Generate Autogenerated Files Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Defines a custom command to generate strings.cpp and version.rc using the prebuild tool. It depends on the prebuild tool and string header files, ensuring regeneration when headers change. ```cmake file(GLOB PREBUILD_STRINGS_FILES LIST_DIRECTORIES false CONFIGURE_DEPENDS strings/*.h ) add_custom_command( OUTPUT ${PROJECT_BINARY_DIR}/strings.cpp ${PROJECT_BINARY_DIR}/version.rc COMMAND "${PREBUILD_TOOL}" ARGS "${PROJECT_SOURCE_DIR}/strings" "${PROJECT_BINARY_DIR}" DEPENDS cppwinrt-prebuild ${PREBUILD_STRINGS_FILES} VERBATIM ) ``` -------------------------------- ### Generate WinRT Projection Files with file_writers Source: https://context7.com/microsoft/cppwinrt/llms.txt Orchestrates the emission of generated C++/WinRT projection files. These functions compose output writers with string fragments and type data, flushing to disk only when content changes. ```cpp #include "file_writers.h" // ── After settings and cache are populated ─────────────────────────────── // Generate winrt/base.h (the core runtime support header): // includes base_macros, base_abi, base_com_ptr, base_error, base_events, // base_implements, base_coroutine_threadpool, base_natvis, etc. cppwinrt::write_base_h(); // → writes to: /winrt/base.h ``` ```cpp // Generate projection headers for a single namespace: // Pass 0 = forward declarations (enums, interface/class/struct/delegate forwards) cppwinrt::write_namespace_0_h("Windows.Foundation", members); // → writes to: /winrt/impl/Windows.Foundation.0.h // Pass 1 = ABI interface declarations cppwinrt::write_namespace_1_h("Windows.Foundation", members); // → writes to: /winrt/impl/Windows.Foundation.1.h // Pass 2 = Producer/consumer shim bodies cppwinrt::write_namespace_2_h("Windows.Foundation", members); // → writes to: /winrt/impl/Windows.Foundation.2.h // Top-level namespace header (pulls in 0/1/2 and provides projected types) cppwinrt::write_namespace_h(cache, "Windows.Foundation", members); // → writes to: /winrt/Windows.Foundation.h ``` ```cpp // Generate Fast Forward vtable helper (only when -fastabi is set and // component classes with FastAbiAttribute are present): std::vector classes = { /* ... */ }; cppwinrt::write_fast_forward_h(classes); // → writes to: /winrt/fast_forward.h ``` ```cpp // Generate component files for each runtime class: for (auto& type : classes) { cppwinrt::write_component_g_h(type); // MyClass.g.h — generated, do not edit cppwinrt::write_component_g_cpp(type); // MyClass.g.cpp — generated, do not edit cppwinrt::write_component_h(type); // MyClass.h — editable skeleton cppwinrt::write_component_cpp(type); // MyClass.cpp — editable skeleton } // Generate the module.g.cpp entry-point file cppwinrt::write_module_g_cpp(classes); // → writes to: /module.g.cpp ``` -------------------------------- ### Enable Test Sanitizers Source: https://github.com/microsoft/cppwinrt/blob/master/test/CMakeLists.txt Configures the build to enable AddressSanitizer (ASan) and UndefinedBehaviorSanitizer (UBSan) for tests. It also disables the 'vptr' check to avoid false positives with COM classes. ```cmake set(ENABLE_TEST_SANITIZERS FALSE CACHE BOOL "Enable ASan and UBSan for the tests.") if(ENABLE_TEST_SANITIZERS) # Disable the 'vptr' check because it seems to produce false-positives when using COM classes. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,address -fno-sanitize=vptr") endif() ``` -------------------------------- ### Configure CppWinRT NuGet Package Properties Source: https://context7.com/microsoft/cppwinrt/llms.txt Customize CppWinRT build behavior by setting properties in your .vcxproj or Directory.Build.props file. These settings control aspects like library linking, build verbosity, namespace conventions, and optimization flags. ```xml false high true true true 1 $(CppWinRTParameters) -ignore_velocity "C:\\Tools\\cppwinrt\\bin\" ``` -------------------------------- ### Set Windows Target Version Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt On Windows, this sets the minimum target version to Windows 8 (0x0602) because WinMD uses CreateFile2, which requires this version or later. ```cmake if(WIN32) # WinMD uses CreateFile2 which requires Windows 8. add_compile_definitions(_WIN32_WINNT=0x0602) endif() ``` -------------------------------- ### Resolving and Sorting WinRT Interfaces with `get_interfaces` Source: https://context7.com/microsoft/cppwinrt/llms.txt The `get_interfaces` function enumerates, deduplicates, and sorts WinRT interfaces implemented by a class. For Fast ABI, it sorts exclusive non-overridable interfaces into a stable vtable order. Use `has_fastabi_tearoffs` to check for tearoff interfaces and `get_fastabi_size` for the total Fast ABI vtable size. ```cpp #include "helpers.h" cppwinrt::writer w; winmd::reader::TypeDef class_type = /* e.g. Windows.UI.Xaml.Controls.Button */; // Returns vector> auto interfaces = cppwinrt::get_interfaces(w, class_type); for (auto& [name, info] : interfaces) { std::printf("interface: %s\n", name.c_str()); std::printf(" is_default: %s\n", info.is_default ? "yes" : "no"); std::printf(" is_protected:%s\n", info.is_protected ? "yes" : "no"); std::printf(" overridable: %s\n", info.overridable ? "yes" : "no"); std::printf(" base: %s\n", info.base ? "yes" : "no"); std::printf(" exclusive: %s\n", info.exclusive ? "yes" : "no"); std::printf(" fastabi: %s\n", info.fastabi ? "yes" : "no"); // relative_version: {contractIndex, version} for fastabi vtable ordering std::printf(" rel_version: {%u, %u}\n", info.relative_version.first, info.relative_version.second); } // Fast ABI: check whether tearoff interfaces exist beyond the default bool has_tearoffs = cppwinrt::has_fastabi_tearoffs(w, class_type); // Get total Fast ABI vtable size (6 base slots + base classes + exclusive methods) std::size_t vtable_size = cppwinrt::get_fastabi_size(w, class_type); std::printf("Fast ABI vtable slots: %zu\n", vtable_size); ``` -------------------------------- ### Build C++/WinRT Projection Target Source: https://github.com/microsoft/cppwinrt/blob/master/test/CMakeLists.txt Defines a custom target 'build-cppwinrt-projection'. This target ensures the C++/WinRT projection headers are generated, either by using a pre-configured include path or by running the 'cppwinrt' tool. ```cmake if(STANDALONE_TESTING) add_custom_target(build-cppwinrt-projection) set(CPPWINRT_PROJECTION_INCLUDE_DIR "" CACHE PATH "Include path for the C++/WinRT projection headers") if(NOT CPPWINRT_PROJECTION_INCLUDE_DIR) message(FATAL_ERROR "CPPWINRT_PROJECTION_INCLUDE_DIR is not specified.") endif() else() set(CPPWINRT_PROJECTION_INCLUDE_DIR "${CMAKE_CURRENT_BINARY_DIR}/cppwinrt") add_custom_command( OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/cppwinrt/winrt/base.h" COMMAND cppwinrt -input local -output "${CPPWINRT_PROJECTION_INCLUDE_DIR}" -verbose DEPENDS cppwinrt VERBATIM ) add_custom_target(build-cppwinrt-projection DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/cppwinrt/winrt/base.h" ) endif() include_directories("${CPPWINRT_PROJECTION_INCLUDE_DIR}") ``` -------------------------------- ### Create cppwinrt Executable Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Defines the cppwinrt executable target, linking source files, resources (if on Windows), and headers. It also sets a compile definition for the version string and includes the binary directory for headers. ```cmake add_executable(cppwinrt ${CPPWINRT_SRCS} ${CPPWINRT_RESOURCES} ${CPPWINRT_HEADERS}) target_compile_definitions(cppwinrt PRIVATE CPPWINRT_VERSION_STRING="${CPPWINRT_BUILD_VERSION}") target_include_directories(cppwinrt PRIVATE ${PROJECT_BINARY_DIR}) ``` -------------------------------- ### Set Minimum CMake Version and Project Name Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Specifies the minimum required CMake version and defines the project name and languages. ```cmake cmake_minimum_required(VERSION 3.16) project(cppwinrt LANGUAGES CXX) ``` -------------------------------- ### Check for windowsnumerics.impl.h Header Source: https://github.com/microsoft/cppwinrt/blob/master/test/CMakeLists.txt This function verifies the availability of the windowsnumerics.impl.h header, which is required for certain tests. If not found and DOWNLOAD_WINDOWSNUMERICS is true, it attempts to download the header. ```cmake function(TestHasWindowsnumerics OUTPUT_VARNAME) include(CheckCXXSourceCompiles) check_cxx_source_compiles("\n#define _WINDOWS_NUMERICS_NAMESPACE_ winrt::Windows::Foundation::Numerics\n#define _WINDOWS_NUMERICS_BEGIN_NAMESPACE_ namespace winrt::Windows::Foundation::Numerics\n#define _WINDOWS_NUMERICS_END_NAMESPACE_\n#include \nint main() {} " ${OUTPUT_VARNAME}) endfunction() TestHasWindowsnumerics(HAS_WINDOWSNUMERICS) set(DOWNLOAD_WINDOWSNUMERICS FALSE CACHE BOOL "Whether to download a copy of mingw-w64's windowsnumerics.impl.h if not available.") if(NOT HAS_WINDOWSNUMERICS AND DOWNLOAD_WINDOWSNUMERICS) file( DOWNLOAD https://github.com/mingw-w64/mingw-w64/raw/2b6272b31132e156dd1fc3722c1aa96b705a90dd/mingw-w64-headers/include/windowsnumerics.impl.h "${CMAKE_CURRENT_BINARY_DIR}/windowsnumerics/windowsnumerics.impl.h" EXPECTED_HASH SHA256=aff42491e57583c8ad8ca8e71d417a553bd1215ee9a71378679400ecded4b1ab SHOW_PROGRESS ) include_directories("${CMAKE_CURRENT_BINARY_DIR}/windowsnumerics") set(HAS_WINDOWSNUMERICS TRUE) message(STATUS "Using windowsnumerics.impl.h downloaded from mingw-w64") endif() ``` -------------------------------- ### Accessing WinRT Method Metadata with `method_signature` Source: https://context7.com/microsoft/cppwinrt/llms.txt The `method_signature` helper provides structured access to parameters, return types, and async classification from a WinMD `MethodDef`. It's used for generating ABI and projected method signatures. Access parameters via `sig.params()`, return type via `sig.return_signature()`, and the return variable name via `sig.return_param_name()`. ```cpp #include "helpers.h" // Given a MethodDef from the winmd reader cache: winmd::reader::MethodDef method = /* ... from cache::namespace_members ... */; cppwinrt::method_signature sig{ method }; // Access parameter list as (Param, ParamSig*) pairs for (auto& [param, param_sig] : sig.params()) { std::printf("param: %s\n", std::string(param.Name()).c_str()); } // Return type signature (nullopt if void) auto& ret = sig.return_signature(); if (ret) { // non-void method } // Name used in generated code for the return value variable std::string_view ret_name = sig.return_param_name(); // → "winrt_impl_result" unless a [out, retval] param named otherwise // Check if the method participates in async parameter lifetime extension // (IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, // IAsyncOperationWithProgress, or property setters) bool async = sig.is_async(); // Access the underlying MethodDef auto& m = sig.method(); std::printf("method name: %s\n", std::string(m.Name()).c_str()); ``` -------------------------------- ### Link libxmllite on Windows Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt This command links the libxmllite library to the cppwinrt target when building on a Windows system. ```cmake target_link_libraries(cppwinrt "${XMLLITE_LIBRARY}") ``` -------------------------------- ### Update Activation Factory for Static Library Consumption Source: https://github.com/microsoft/cppwinrt/blob/master/test/nuget/TestStaticLibrary7/readme.txt Update the activation factory in the consuming binary to call the activation factory exposed by this static library. This is necessary to instantiate types from the static library. ```cpp void* __stdcall TestStaticLibrary7_get_activation_factory( std::wstring_view const& name); void* __stdcall winrt_get_activation_factory( std::wstring_view const& name) { void* factory = TestStaticLibrary7_get_activation_factory(name); if (factory) { return factory; } /* call other activation factories */ return nullptr; } ``` -------------------------------- ### Use External winmd Library Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt If an external winmd library is provided, this configuration uses the specified include directory. It then adds this directory to the cppwinrt target's include paths. ```cmake message(STATUS "Using winmd library headers at ${EXTERNAL_WINMD_INCLUDE_DIR}") set(winmd_INCLUDE_DIR "${EXTERNAL_WINMD_INCLUDE_DIR}") target_include_directories(cppwinrt PRIVATE "${winmd_INCLUDE_DIR}") ``` -------------------------------- ### settings_type Structure Definition Source: https://context7.com/microsoft/cppwinrt/llms.txt Defines the runtime settings for cppwinrt.exe, controlling code generation decisions. It holds input/output paths, flags for various generation options, and namespace filtering. ```cpp // cppwinrt/settings.h namespace cppwinrt { struct settings_type { std::set input; // resolved .winmd paths to project std::set reference; // resolved .winmd paths to reference only std::string output_folder; // canonical path with trailing separator bool base{}; // write base.h unconditionally bool license{}; // prepend license header std::string license_template; // raw license text bool brackets{}; // use <> for #includes instead of "" bool verbose{}; // verbose console output bool component{}; // generate component skeletons std::string component_folder; // where component files go std::string component_name; // prefix stripped from type names std::string component_pch; // PCH name used in generated .cpp files bool component_prefix{}; // dotted namespace vs. folder convention bool component_overwrite{}; // overwrite existing skeleton files std::string component_lib; // namespace prefix (default "winrt") bool component_opt{}; // optimized component projection bool component_ignore_velocity{}; // ignore feature-staging metadata std::set include; // namespace prefixes to include std::set exclude; // namespace prefixes to exclude winmd::reader::filter projection_filter; // computed from reference split winmd::reader::filter component_filter; // computed from include/exclude bool fastabi{}; // Fast ABI mode std::map fastabi_cache; // default iface → class }; extern settings_type settings; // single global instance populated by process_args() } ``` -------------------------------- ### settings_type Structure Definition Source: https://context7.com/microsoft/cppwinrt/llms.txt Defines the runtime settings for cppwinrt.exe, controlling code generation decisions. It holds input/output paths, flags for various generation options, and namespace filtering. ```cpp #include "cmd_reader.h" // Define the accepted options table static constexpr cppwinrt::option my_options[] { { "input", 0, cppwinrt::option::no_max, "", "Input WinMD" }, { "output", 0, 1, "", "Output path" }, { "verbose", 0, 0, {}, "Verbose" }, }; int main(int argc, char** argv) { // Construction validates min/max counts and throws std::invalid_argument on error cppwinrt::reader args{ argc, argv, my_options }; if (!args) // operator bool() — false if no args provided { std::puts("No arguments supplied"); return 1; } // Check flag presence bool verbose = args.exists("verbose"); // Get single value with optional default std::string out = args.value("output", "."); // Get all values for a multi-value option for (auto& v : args.values("input")) { std::printf("input: %s\n", v.c_str()); } // Resolve files — expands directories, SDK specs ("sdk", "sdk+", // "10.0.19041.0"), and "local" (%WinDir%\System32\WinMetadata) // using a filter predicate (e.g., only .winmd files) auto winmd_files = args.files("input", [](std::string const& path) { return path.ends_with(".winmd"); }); for (auto& f : winmd_files) std::printf("resolved: %s\n", f.c_str()); return 0; } // Example invocation: // my_tool.exe -input sdk -input MyLib.winmd -output .\out -verbose // Resolved winmd_files would contain every .winmd in the current Windows SDK // plus the absolute canonical path to MyLib.winmd. ``` -------------------------------- ### Generate libxmllite for MinGW Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt This snippet generates the libxmllite.a library for MinGW environments when an external libxmllite is not found. It uses CMake's custom command and DLL tool to create the library from a .def file. ```cmake add_custom_command( OUTPUT "${PROJECT_BINARY_DIR}/libxmllite.a" COMMAND "${CMAKE_DLLTOOL}" -k -d "${PROJECT_SOURCE_DIR}/mingw-support/${XMLLITE_DEF_FILE}.def" -l "${PROJECT_BINARY_DIR}/libxmllite.a" DEPENDS "${PROJECT_SOURCE_DIR}/mingw-support/${XMLLITE_DEF_FILE}.def" VERBATIM ) add_custom_target(gen-libxmllite DEPENDS "${PROJECT_BINARY_DIR}/libxmllite.a" ) set(XMLLITE_LIBRARY "${PROJECT_BINARY_DIR}/libxmllite.a") add_dependencies(cppwinrt gen-libxmllite) ``` -------------------------------- ### Consuming Activation Factory in Runtime Component Source: https://github.com/microsoft/cppwinrt/blob/master/vsix/ProjectTemplates/VC/Windows Universal/StaticLibrary/readme.txt Update the activation factory in the consuming binary to call the activation factory exposed by this static library. This function is called when a Windows Runtime type is activated. ```cpp void* __stdcall $projectname$_get_activation_factory( std::wstring_view const& name); void* __stdcall winrt_get_activation_factory( std::wstring_view const& name) { void* factory = $projectname$_get_activation_factory(name); if (factory) { return factory; } /* call other activation factories */ return nullptr; } ``` -------------------------------- ### Set CppWinRTVerbosity for MSBuild Source: https://github.com/microsoft/cppwinrt/blob/master/nuget/readme.md Override the default importance of C++/WinRT build messages to control throttling. Use this when you need to see more or fewer C++/WinRT specific messages, independent of the overall MSBuild verbosity. ```bash msbuild project.vcxproj /verbosity:minimal /property:CppWinRTVerbosity=high ... ``` -------------------------------- ### Extract WinRT Factory Metadata with get_factories() Source: https://context7.com/microsoft/cppwinrt/llms.txt Reads custom attributes from a WinRT class TypeDef to describe available factory interfaces. Use this to understand the activation, static, composable, and visibility properties of a class's factories. ```cpp #include "helpers.h" cppwinrt::writer w; winmd::reader::TypeDef class_type = /* e.g. Windows.UI.Xaml.Controls.TextBox */; // Returns map auto factories = cppwinrt::get_factories(w, class_type); for (auto& [factory_name, fi] : factories) { std::printf("factory interface: '%s'\n", factory_name.c_str()); std::printf(" activatable: %s\n", fi.activatable ? "yes" : "no"); std::printf(" statics: %s\n", fi.statics ? "yes" : "no"); std::printf(" composable: %s\n", fi.composable ? "yes" : "no"); std::printf(" visible: %s\n", fi.visible ? "yes" : "no"); // fi.type — the TypeDef of the factory interface (may be null for // default-activatable classes with no explicit factory interface) } // Helper predicates built on get_factories(): bool has_members = cppwinrt::has_factory_members(w, class_type); bool is_comp = cppwinrt::is_composable(w, class_type); bool has_comp_ctor = cppwinrt::has_composable_constructors(w, class_type); ``` -------------------------------- ### Add Test Subdirectories Source: https://github.com/microsoft/cppwinrt/blob/master/test/CMakeLists.txt Includes various test subdirectories into the build. These subdirectories contain specific test suites, such as those for coroutines, C++20 features, and older tests. ```cmake add_subdirectory(test) add_subdirectory(test_nocoro) add_subdirectory(test_cpp20) add_subdirectory(test_cpp20_no_sourcelocation) if(HAS_WINDOWSNUMERICS) add_subdirectory(old_tests) endif() ``` -------------------------------- ### Define cppwinrt Build Version Source: https://github.com/microsoft/cppwinrt/blob/master/CMakeLists.txt Sets the build version for cppwinrt, with a warning for dummy versions. This version string is used for generated files and can be overridden via CMake arguments. ```cmake set(CPPWINRT_BUILD_VERSION "999.999.999.999" CACHE STRING "The version string used for cppwinrt.") if(CPPWINRT_BUILD_VERSION STREQUAL "999.999.999.999" OR CPPWINRT_BUILD_VERSION STREQUAL "0.0.0.0") message(WARNING "CPPWINRT_BUILD_VERSION has been set to a dummy version string. Do not use in production!") endif() message(STATUS "Using version string: ${CPPWINRT_BUILD_VERSION}") ``` -------------------------------- ### Use ComponentConnectorT for Derived Classes with Markup Source: https://github.com/microsoft/cppwinrt/blob/master/nuget/readme.md For objects with markup that derive from composable base classes, use ComponentConnectorT to provide a correct implementation for IComponentConnector::Connect and IComponentConnector2::GetBindingConnector. This handles callbacks to the most derived implementations. ```cpp struct DerivedPage : winrt::Windows::UI::Xaml::Markup::ComponentConnectorT> ``` -------------------------------- ### Enable ANSI Color Output for Tests Source: https://github.com/microsoft/cppwinrt/blob/master/test/CMakeLists.txt Enables ANSI color output for the Catch2 test runner. This is controlled by the USE_ANSI_COLOR variable and adds a compile definition and a test argument. ```cmake set(USE_ANSI_COLOR FALSE CACHE BOOL "Enable ANSI colour output for Catch2 test runner.") if(USE_ANSI_COLOR) add_compile_definitions(CATCH_CONFIG_COLOUR_ANSI) set(TEST_COLOR_ARG "--use-colour yes") endif() ``` -------------------------------- ### Override InitializeComponent for Xaml Property Access Source: https://github.com/microsoft/cppwinrt/blob/master/nuget/readme.md If a Xaml object needs to access a Xaml property during initialization, override InitializeComponent and call the base class's InitializeComponent first. This ensures proper registration with the Xaml runtime before accessing properties. ```cpp void MainPage::InitializeComponent() { // Call base InitializeComponent() to register with the Xaml runtime MainPageT::InitializeComponent(); // Can now access Xaml properties MyButton().Content(box_value(L"Click")); } ``` -------------------------------- ### Avoid Explicit InitializeComponent Calls in Constructors Source: https://github.com/microsoft/cppwinrt/blob/master/nuget/readme.md In older versions of C++/WinRT, explicit calls to InitializeComponent from constructors could cause memory corruption if InitializeComponent threw an exception. This pattern should no longer be used. ```cpp void MainPage::MainPage() { // This pattern should no longer be used InitializeComponent(); } ``` -------------------------------- ### Override InitializeComponent with ComponentConnectorT Base Call Source: https://github.com/microsoft/cppwinrt/blob/master/nuget/readme.md When overriding InitializeComponent in a class that uses ComponentConnectorT, explicitly call ComponentConnectorT::InitializeComponent() instead of the derived template's InitializeComponent. This ensures proper registration with the Xaml runtime. ```cpp void DerivedPage::InitializeComponent() { // Call base InitializeComponent() to register with the Xaml runtime ComponentConnectorT::InitializeComponent(); // Can now access Xaml properties from base or derived class MyBaseButton().Content(box_value(L"Click")); } ``` -------------------------------- ### Check for x86_64 Architecture Source: https://github.com/microsoft/cppwinrt/blob/master/test/CMakeLists.txt This function checks if the target architecture is x86_64 using C++ preprocessor directives. It's used to conditionally apply specific compiler flags. ```cmake function(TestIsX64 OUTPUT_VARNAME) include(CheckCXXSourceCompiles) check_cxx_source_compiles("\n#if !defined(__x86_64__) && !defined(_M_X64)\n#error Not x86_64\n#endif\nint main() {} " ${OUTPUT_VARNAME}) endfunction() TestIsX64(TARGET_IS_X64) if(TARGET_IS_X64) add_compile_options(-mcx16) endif() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.