Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to define DLLImport with EntryPoint attribute

Tags:

c++

c#

pinvoke

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?

like image 552
Simsons Avatar asked Jun 21 '12 09:06

Simsons


1 Answers

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.

like image 165
Jon Avatar answered Oct 23 '22 15:10

Jon