use*_*871 2 c++ windows-runtime wrl
当我使用WRL创建winrt组件时,问题是我只能使用ABI::Windows::xxx命名空间,而且我不能Windows::UI::Xaml::Media::Imaging在WRL中使用命名空间.
那么,如何创建内置winrt组件作为返回值?
// idl
import "inspectable.idl";
import "Windows.Foundation.idl";
import "Windows.UI.Xaml.Media.Imaging.idl";
namespace Decoder
{
interface IPhotoDecoder;
runtimeclass PhotoDecoder;
interface IPhotoDecoder : IInspectable
{
HRESULT Decode([in] int width, [in] int height, [out, retval] Windows.UI.Xaml.Media.Imaging.BitmapImage **ppBitmapImage);
}
[version(COMPONENT_VERSION), activatable(COMPONENT_VERSION)]
runtimeclass PhotoDecoder
{
[default] interface IPhotoDecoder;
}
}
// cpp
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
using namespace ABI::Windows::UI::Xaml::Media::Imaging;
namespace ABI
{
namespace Decoder
{
class PhotoDecoder: public RuntimeClass<IPhotoDecoder>
{
InspectableClass(L"Decoder.PhotoDecoder", BaseTrust)
public:
PhotoDecoder()
{
}
HRESULT __stdcall Decode(_In_ int width, _In_ int height, _Out_ IBitmapImage **ppBitmapImage)
{
// How to create Windows.UI.Xaml.Media.Imaging.BitmapImage without using Windows::UI::Xaml::Media::Imaging
}
};
ActivatableClass(PhotoDecoder);
}
}
Run Code Online (Sandbox Code Playgroud)
有两组命名空间:
Windows::Foundation)ABI命名空间的人(例如ABI::Windows::Foundation)每个的内容都是"相同的".例如,Windows::Foundation::IUriRuntimeClass将相同的接口命名为ABI::Windows::Foundation::IUriRuntimeClass.
那么,为什么有两组命名空间?以全局命名空间为根的名称空间保留供C++/CX使用:它在这些名称空间中生成运行时类的投影.当您使用WRL时,您将始终使用以命名空间为根的ABI名称空间(这是"未经注册的"名称,也就是说,它们正是ABI层中存在的名称).
运行时类以两种方式之一实例化("激活").如果类型是默认可构造的,则可以通过调用默认构造RoActivateInstance.如果类型声明了其他构造函数,则可以通过调用获取运行时类型的激活工厂来调用这些构造函数RoGetActivationFactory.例如,您可以默认构造BitmapImage如下:
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::UI::Xaml::Media::Imaging;
HStringReference classId(RuntimeClass_Windows_UI_Xaml_Media_Imaging_BitmapImage);
ComPtr<IInspectable> inspectable;
if (FAILED(RoActivateInstance(classId.Get(), inspectable.GetAddressOf())))
{
// Handle failure
}
ComPtr<IBitmapImage> bitmapImage;
if (FAILED(inspectable.As(&bitmapImage)))
{
// Handle failure
}
Run Code Online (Sandbox Code Playgroud)
WRL还有一个有用的功能模板,Windows::Foundation::ActivateInstance它既调用RoActivateInstance又执行QueryInterface所需的目标接口:
using namespace Windows::Foundation;
ComPtr<IBitmapImage> bitmapImage;
if (FAILED(ActivateInstance(classId.Get(), bitmapImage.GetAddressOf())))
{
// Handle failure
}
Run Code Online (Sandbox Code Playgroud)