This topic shows how to convert between SDK application binary interface (ABI) and C++/WinRT objects. You can use these techniques to interop between code that uses these two ways of programming with the Windows Runtime, or you can use them as you gradually move your code from the ABI to C++/WinRT.
In general, C++/WinRT exposes ABI types as void*, so that you don't need to include platform header files.
Notitie
In the code examples, we use reinterpret_cast (rather than static_cast) in an effort to telegraph what are inherently unsafe casts.
What is the Windows Runtime ABI, and what are ABI types?
A Windows Runtime class (runtime class) is really an abstraction. This abstraction defines a binary interface (the Application Binary Interface, or ABI) that allows various programming languages to interact with an object. Regardless of programming language, client code interaction with a Windows Runtime object happens at the lowest level, with client language constructs translated into calls into the object's ABI.
The Windows SDK headers in the folder "%WindowsSdkDir%Include\10.0.17134.0\winrt" (adjust the SDK version number for your case, if necessary), are the Windows Runtime ABI header files. They were produced by the MIDL compiler. Here's an example of including one of these headers.
C++
#include<windows.foundation.h>
And here's a simplified example of one of the ABI types that you'll find in that particular SDK header. Note the ABI namespace; Windows::Foundation, and all other Windows namespaces, are declared by the SDK headers within the ABI namespace.
IUriRuntimeClass is a COM interface. But more than that—since its base is IInspectable—IUriRuntimeClass is a Windows Runtime interface. Note the HRESULT return type, rather than the raising of exceptions. And the use of artifacts such as the HSTRING handle (it's good practice to set that handle back to nullptr when you're finished with it). This gives a taste of what the Windows Runtime looks like at the application binary level; in other words, at the COM programming level.
The Windows Runtime is based on Component Object Model (COM) APIs. You can access the Windows Runtime that way, or you can access it through language projections. A projection hides the COM details, and provides a more natural programming experience for a given language.
For example, if you look in the folder "%WindowsSdkDir%Include\10.0.17134.0\cppwinrt\winrt" (again, adjust the SDK version number for your case, if necessary), then you'll find the C++/WinRT language projection headers. There's a header for each Windows namespace, just like there's one ABI header per Windows namespace. Here's an example of including one of the C++/WinRT headers.
C++/WinRT
#include<winrt/Windows.Foundation.h>
And, from that header, here (simplified) is the C++/WinRT equivalent of that ABI type we just saw.
The interface here is modern, standard C++. It does away with HRESULTs (C++/WinRT raises exceptions if necessary). And the accessor function returns a simple string object, which is cleaned up at the end of its scope.
This topic is for cases when you want to interop with, or port, code that works at the Application Binary Interface (ABI) layer.
Converting to and from ABI types in code
For safety and simplicity, for conversions in both directions you can simply use winrt::com_ptr, com_ptr::as, and winrt::Windows::Foundation::IUnknown::as. Here's a code example (based on the Console App project template), which also illustrates how you can use namespace aliases for the different islands to deal with otherwise potential namespace collisions between the C++/WinRT projection and the ABI.
C++/WinRT
// pch.h#pragma once#include<windows.foundation.h>#include<unknwn.h>#include"winrt/Windows.Foundation.h"// main.cpp#include"pch.h"namespace winrt
{
usingnamespace Windows::Foundation;
}
namespace abi
{
usingnamespace ABI::Windows::Foundation;
};
intmain(){
winrt::init_apartment();
winrt::Uri uri(L"http://aka.ms/cppwinrt");
// Convert to an ABI type.
winrt::com_ptr<abi::IStringable> ptr{ uri.as<abi::IStringable>() };
// Convert from an ABI type.
uri = ptr.as<winrt::Uri>();
winrt::IStringable uriAsIStringable{ ptr.as<winrt::IStringable>() };
}
The implementations of the as functions call QueryInterface. If you want lower-level conversions that only call AddRef, then you can use the winrt::copy_to_abi and winrt::copy_from_abi helper functions. This next code example adds these lower-level conversions to the code example above.
Belangrijk
When interoperating with ABI types it's critical that the ABI type used corresponds to the default interface of the C++/WinRT object. Otherwise, invocations of methods on the ABI type will actually end up calling methods in the same vtable slot on the default interface with very unexpected results. Note that winrt::copy_to_abi does not protect against this at compile time since it uses void* for all ABI types and assumes that the caller has been careful not to mis-match the types. This is to avoid requiring C++/WinRT headers to reference ABI headers when ABI types may never be used.
C++/WinRT
intmain(){
// The code in main() already shown above remains here.// Lower-level conversions that only call AddRef.// Convert to an ABI type.
ptr = nullptr;
winrt::copy_to_abi(uriAsIStringable, *ptr.put_void());
// Convert from an ABI type.
uri = nullptr;
winrt::copy_from_abi(uriAsIStringable, ptr.get());
ptr = nullptr;
}
Here are other similarly low-level conversions techniques but using raw pointers to ABI interface types (those defined by the Windows SDK headers) this time.
C++/WinRT
// The code in main() already shown above remains here.// Copy to an owning raw ABI pointer with copy_to_abi.
abi::IStringable* owning{ nullptr };
winrt::copy_to_abi(uriAsIStringable, *reinterpret_cast<void**>(&owning));
// Copy from a raw ABI pointer.
uri = nullptr;
winrt::copy_from_abi(uriAsIStringable, owning);
owning->Release();
WINRT_ASSERT is a macro definition, and it expands to _ASSERTE.
C++/WinRT
// The code in main() already shown above remains here.// Lowest-level conversions that only copy addresses// Convert to a non-owning ABI object with get_abi.
abi::IStringable* non_owning{ reinterpret_cast<abi::IStringable*>(winrt::get_abi(uriAsIStringable)) };
WINRT_ASSERT(non_owning);
// Avoid interlocks this way.
owning = reinterpret_cast<abi::IStringable*>(winrt::detach_abi(uriAsIStringable));
WINRT_ASSERT(!uriAsIStringable);
winrt::attach_abi(uriAsIStringable, owning);
WINRT_ASSERT(uriAsIStringable);
convert_from_abi function
This helper function converts a raw ABI interface pointer to an equivalent C++/WinRT object, with minimal overhead.
C++/WinRT
template <typename T>
T convert_from_abi(::IUnknown* from){
T to{ nullptr }; // `T` is a projected type.
winrt::check_hresult(from->QueryInterface(winrt::guid_of<T>(),
winrt::put_abi(to)));
return to;
}
The function simply calls QueryInterface to query for the default interface of the requested C++/WinRT type.
As we've seen, a helper function is not required to convert from a C++/WinRT object to the equivalent ABI interface pointer. Simply use the winrt::Windows::Foundation::IUnknown::as (or try_as) member function to query for the requested interface. The as and try_as functions return a winrt::com_ptr object wrapping the requested ABI type.
Code example using convert_from_abi
Here's a code example showing this helper function in practice.
C++/WinRT
// pch.h#pragma once#include<windows.foundation.h>#include<unknwn.h>#include"winrt/Windows.Foundation.h"// main.cpp#include"pch.h"#include<iostream>usingnamespace winrt;
usingnamespace Windows::Foundation;
namespace winrt
{
usingnamespace Windows::Foundation;
}
namespace abi
{
usingnamespace ABI::Windows::Foundation;
};
namespace sample
{
template <typename T>
T convert_from_abi(::IUnknown* from){
T to{ nullptr }; // `T` is a projected type.
winrt::check_hresult(from->QueryInterface(winrt::guid_of<T>(),
winrt::put_abi(to)));
return to;
}
inlineautoput_abi(winrt::hstring& object)noexcept{
returnreinterpret_cast<HSTRING*>(winrt::put_abi(object));
}
}
intmain(){
winrt::init_apartment();
winrt::Uri uri(L"http://aka.ms/cppwinrt");
std::wcout << "C++/WinRT: " << uri.Domain().c_str() << std::endl;
// Convert to an ABI type.
winrt::com_ptr<abi::IUriRuntimeClass> ptr = uri.as<abi::IUriRuntimeClass>();
winrt::hstring domain;
winrt::check_hresult(ptr->get_Domain(sample::put_abi(domain)));
std::wcout << "ABI: " << domain.c_str() << std::endl;
// Convert from an ABI type.
winrt::Uri uri_from_abi = sample::convert_from_abi<winrt::Uri>(ptr.get());
WINRT_ASSERT(uri.Domain() == uri_from_abi.Domain());
WINRT_ASSERT(uri == uri_from_abi);
}
Interoperating with ABI COM interface pointers
The helper function template below illustrates how to copy an ABI COM interface pointer of a given type to its equivalent C++/WinRT projected smart pointer type.
C++/WinRT
template<typename To, typename From>
To to_winrt(From* ptr){
To result{ nullptr };
winrt::check_hresult(ptr->QueryInterface(winrt::guid_of<To>(), winrt::put_abi(result)));
return result;
}
...
ID2D1Factory1* com_ptr{ ... };
auto cppwinrt_ptr {to_winrt<winrt::com_ptr<ID2D1Factory1>>(com_ptr)};
The table that follows shows (in addition to other operations) unsafe conversions between an ABI COM interface pointer of a given type and its equivalent C++/WinRT projected smart pointer type. For the code in the table, assume these declarations.
s takes ownership of the object. Any object previously owned by s is leaked (will assert in debug).
Replace ISample* in winrt::Sample
attach_abi(s, p);
s takes ownership of the object. The object previously owned by s is freed.
Copy ISample* to winrt::Sample
copy_from_abi(s, p);
s makes a new reference to the object. The object previously owned by s is freed.
Copy winrt::Sample to ISample*
copy_to_abi(s, reinterpret_cast<void*&>(p));
p receives a copy of the object. Any object previously owned by p is leaked.
Interoperating with the ABI's GUID struct
GUID (/previous-versions/aa373931(v%3Dvs.80)) is projected as winrt::guid. For APIs that you implement, you must use winrt::guid for GUID parameters. Otherwise, there are automatic conversions between winrt::guid and GUID as long as you include unknwn.h (implicitly included by <windows.h> and many other header files) before you include any C++/WinRT headers.
If you don't do that, then you can hard-reinterpret_cast between them. For the table that follows, assume these declarations.
For a gist showing how to construct a winrt::guid from a string, see make_guid.cpp.
Interoperating with the ABI's HSTRING
The table that follows shows conversions between winrt::hstring and HSTRING, and other operations. For the code in the table, assume these declarations.
s takes ownership of string. Any string previously owned by s is leaked (will assert in debug).
Replace HSTRING in hstring
attach_abi(s, h);
s takes ownership of string. The string previously owned by s is freed.
Copy HSTRING to hstring
copy_from_abi(s, h);
s makes a private copy of the string. The string previously owned by s is freed.
Copy hstring to HSTRING
copy_to_abi(s, reinterpret_cast<void*&>(h));
h receives a copy of the string. Any string previously owned by h is leaked.
In addition, the Windows Implementation Libraries (WIL) string helpers perform basic string manipulations. To use the WIL string helpers, include <wil/resource.h>, and refer to the table below. Follow the links in the table for full details.
Operation
WIL string helper for more info
Provide a raw Unicode or ANSI string pointer and an optional length; obtain a suitably-specialized unique_any wrapper
Azure HPC is een speciaal gebouwde cloudmogelijkheid voor HPC & AI-workload, met behulp van toonaangevende processors en HPC-klasse InfiniBand-interconnect, om de beste toepassingsprestaties, schaalbaarheid en waarde te leveren. Met Azure HPC kunnen gebruikers innovatie, productiviteit en bedrijfsflexibiliteit ontgrendelen via een maximaal beschikbare reeks HPC & AI-technologieën die dynamisch kunnen worden toegewezen wanneer uw bedrijf en technische behoeften veranderen. Dit leertraject is een reeks module