Search code examples
vb.netpinvoke

What does it take to pInvoke CreateFileMapping?


I'm not a fan of pInvokes but I don't think I have any other choice on this one, I need to resize memory mapped files in vb.net. Anyways, I got this pInvoke signature from pinvoke.net:

<DllImport("kernel32.dll", SetLastError:= true, CharSet:= CharSet.Auto)> _
public Function CreateFileMapping( _
 hFile as intptr, _
 lpFileMappingAttributes As IntPtr , _
 flProtect As FileMapProtection, _
 dwMaximumSizeHigh As UInteger, _
 dwMaximumSizeLow As UInteger, _
 lpName As <MarshalAs(UnmanagedType.LPTStr)> string) as IntPtr
End Function

Public Enum FileMapProtection As UInteger
    PageReadonly = &H2
    PageReadWrite = &H4
    PageWriteCopy = &H8
    PageExecuteRead = &H20
    PageExecuteReadWrite = &H40
    SectionCommit = &H8000000
    SectionImage = &H1000000
    SectionNoCache = &H10000000
    SectionReserve = &H4000000
End Enum

I have imported System.Runtime.InteropServices but I get an error at the < MarshalAs thingy. I have no idea whats missing or where its from. Don't you just hate it how none of these reference never mention any dependencies anywhere ever? Like I'm supposed to spontaneously know which library or framework branch its from. Usually I can find out by looking at the lefthand tree in MSDN but this time I cant find any direct reference to that command.


Solution

  • The MarshalAs attribute must appear before the parameter rather than in the middle of it.

    <DllImport("kernel32.dll", SetLastError:= true, CharSet:= CharSet.Auto)> _
    public Function CreateFileMapping( _
        hFile as intptr, _
        lpFileMappingAttributes As IntPtr , _
        flProtect As FileMapProtection, _
        dwMaximumSizeHigh As UInteger, _
        dwMaximumSizeLow As UInteger, _
        <MarshalAs(UnmanagedType.LPTStr)> lpName As string) as IntPtr
    End Function
    

    The declaration at pinvoke.net is wrong. As they often are. For what it is worth, the attribute is pointless since UnmanagedType.LPTStr is the default. You can omit this attribute.