Search code examples
silverlightwinapipinvokesilverlight-5.0

pInvoke Win32 function for Marshal.PtrToStructure in Silverlight 5


I used

public static Object PtrToStructure(
IntPtr ptr,
Type structureType
)

in the form of

private static object ReadStruct(byte[] buffer, Type t)
{
    GCHandle handle =
        GCHandle.Alloc(buffer,
        GCHandleType.Pinned);
    Object temp =
        Marshal.PtrToStructure(
        handle.AddrOfPinnedObject(),
        t);
    handle.Free();
    return temp;
}

for marshaling data in .net 4.0. Silverlight does not support this method. According to the following article, the .net method is simply a wrapper for a native win32 function. An example was given for Marshal.AllocHGlobal (Win32 LocalAlloc function from Kernel32.dll)

http://blogs.msdn.com/b/silverlight_sdk/archive/2011/09/27/pinvoke-in-silverlight5-and-net-framework.aspx

These are new waters since SL5 just enabled pInvoke for trusted applications (in browser as well) What is the win32 function that PtrToStructure wraps and is there anything preventing using this in SL5?


Solution

  • Using a decompiler of your choice, you will be able to see that PtrToStructure(IntPtr, Type) is indeed implemented in the mscorlib.dll assembly of Silverlight 5:

    [SecurityCritical]
    [ComVisible(true)]
    [FriendAccessAllowed]
    internal static object PtrToStructure(IntPtr ptr, Type structureType)
    

    Being internal it is however not accessible to other assemblies. PtrToStructure in turn calls the following method:

    [MethodImpl(MethodImplOptions.InternalCall)]
    private static void PtrToStructureHelper(IntPtr ptr, object structure, bool allowValueClasses);
    

    which is implemented in the common language runtime.

    I have not been able to identify the win32 function(s) called by PtrToStructureHelper. However, since the PtrToStructure method holds the [SecurityCritical] attribute it is highly likely that Silverlight P/Invoke calls to these win32 functions, if identified, would lead to security exceptions.