Search code examples
.netpinvokeembedded-resource

.NET embedded resource, getting an IntPtr to the raw memory location for use in unmanaged code


I need to expose a void* and ulong size value to native code that points to a .NET embedded resource.

Now, I could allocate the memory myself and copy the data (using traditional methods), but these files may be large so I'd like to avoid that if I can.

Is there a way to point (via raw pointer) to the embedded resource directly? Either memory, or an offset that can be used to go to the .NET library directly on the file system?


Solution

  • From some tests, embedded resources are loaded as UnmanagedMemoryStream... So:

    // https://stackoverflow.com/a/917607/613130
    UnmanagedMemoryStream stream = (UnmanagedMemoryStream)assembly.GetManifestResourceStream("DefaultNamespaceOfAssembly.FileName.jpg");
    byte* ptr = stream.PositionPointer;
    long length = stream.Length;
    

    From comments in the reference source, the operation shouldn't allocate any memory (the pointer you get should be to the real resource that is loaded in memory). In fact, the UnmanagedMemoryStream doesn't free any memory on Dispose().

    Note that the ulong size you asked is a little fishy... I hope you are sure of it. The unsigned long of VC++ isn't long, and the size_t is a ulong only at 64 bits, and is a uint at 32 bits.