简体   繁体   中英

How to create a RandomAccessStreamReference to access a resource defined in a .rc file?

Working in "traditional" C++, I would like to embed a ONNX file (for usage with WinML) into a DLL as a resource, adding it to the .rc file: IDR_NETWORK ONNX "network.onnx" That is working fine, I can access the resource using the FindResource , LoadResource , and LockResource functions.

For , there is a method LearningModel::LoadFromStream taking a winrt::Windows::Storage::Streams::RandomAccessStreamReference as argument. ,有一个方法LearningModel::LoadFromStreamwinrt::Windows::Storage::Streams::RandomAccessStreamReference作为参数。 That seems to be the right interface to load the network from something else than a file.

I tried with winrt::Windows::Storage::Streams::RandomAccessStreamReference::CreateFromUri but I do not see how to create an URI for the embedded resource.

My current workaround is to extract the resource, save to a temporary file and load using LearningModel::LoadFromFilePath from the temporary file.

Best would be code how to directly access the resource. 代码如何直接访问资源。

Alternativly creating a RandomAccessStreamReference to access the pointer returned by LockResource would help.

The following example (pseudo) code does the trick:

        HRSRC hResource = ::FindResource(hModule, MAKEINTRESOURCE(iRessourceID), L"ONNX"))
        HGLOBAL hMem = ::LoadResource(hModule, hResource)

        const BYTE* pData = (const BYTE*)::LockResource(hMem);
        const size_t iSize = ::SizeofResource(hModule, hResource);

        using namespace Windows::Storage;
        using namespace winrt::Windows::Storage::Streams;

        InMemoryRandomAccessStream modelStream;
        DataWriter writer(modelStream);
        writer.WriteBytes(array_view<const unsigned char>(pData, pData + iSize));
        writer.StoreAsync().get();

        ::FreeResource(hMem);

        modelStream.Seek(0);

        auto modelStreamReference = RandomAccessStreamReference::CreateFromStream(modelStream);
        auto model = LearningModel::LoadFromStream(modelStreamReference);

This codes creates a copy of the data, potentially that could be improved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM