Why do I need to define DLLImport with EntryPoint attribute

c#, c++, pinvoke

Solution

The `EntryPoint` field serves to tell the .NET runtime which function to call from the DLL being invoked; if it's not set, the default is the same name that the .NET method declaration has. In your second example, omitting `EntryPoint = "ReadFile"` would result in the runtime trying to call a function named `ReadFile2` (which does not exist).

The prototype needs to have the `static` and `extern` modifiers because the specification says so. It does not need to be `public`; controlling the visibility of the method is entirely up to you.

Problem

While going through SWig generated wrappers, I find that the PInvokes don't have any entry point defined, but some places do have an entry point. So what is the difference between them? When do I need to define an EntryPoint, and when do I not need to? Defined without `EntryPoint`: ``` [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] public static extern bool ReadFile( HandleRef hndRef, StringBuilder buffer, int numberOfBytesToRead, out int numberOfBytesRead, int flag); ``` Defined with `Entrypoint`: ``` [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "ReadFile")] public static extern bool ReadFile2( HandleRef hndRef, StringBuilder buffer, int numberOfBytesToRead, out int numberOfBytesRead, Overlapped2 flag); ``` Also why does the function have to be `static` as in `public static extern`? I assume that `extern` is telling the compiler that this method is defined externally?

Original source