Take the 2-minute tour ×

HI all,

I would like to call from my C# code, unamanaged library functions like presented below. There are two options and the both works. In this moment "Beep" function is simple and have no input/output parameters, pointers, references... I am wondering in more complex cases what would be adventages and disadvantage of both approches ?

Thanks, Milan.

    public void TestBeep()
        Beep(300, 3000);

    internal delegate bool DelegBeep(uint iFreq, uint iDuration);
    internal static extern IntPtr LoadLibrary(String dllname);
    public void BeepIt()
        IntPtr kernel32 = LoadLibrary("Kernel32.dll");
        IntPtr procBeep = GetProcAddress(kernel32, "Beep");
        delegBeep(50, 1000);//Hz,ms
share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

Your second one is much more complicated than the first but achieves the same thing in this case.

If the name of the DLL and the name of the function are known at compile time, then stick with the first approach. If you don't know the name of the DLL and/or function until run time then the LoadLibary/GetProcAddress approach is your only option.

share|improve this answer
The name of dll I have to know in both cases right ? Otherwise LoadLibrary will return error, or maybe I can give full part to LoadLibrary function ? –  milan Jul 2 '10 at 16:27
Right, but with [DllImport] you have to pass a constant string, whereas a call to LoadLibrary lets you determine the DLL name at runtime. –  Tim Robinson Jul 2 '10 at 16:38
I try to comment out [DllImport("kernel32.dll")] in the second example but then I get exception that LoadLibray have no implementation. How I should call then LoadLibrary ? –  milan Jul 2 '10 at 17:53
I don't follow... why are you commenting out the [DllImport("kernel32.dll")] next to LoadLibrary? –  Tim Robinson Jul 2 '10 at 18:25
Yes I commented out all [DllImport("kernel32.dll")] because I thougt your idea is to use just LoadLibrary with correct library path, or I got it wrong ? –  milan Jul 2 '10 at 18:28
show 6 more comments

The P/Invoke marshaller finds an entrypoint in a DLL by using LoadLibrary() and GetProcAddress(). And knows how to convert a C# declaration to the equivalent of a delegate declaration.

Doing this yourself has no advantage beyond maybe a wee bit of efficiency. Which you'd better measure, it is no slamdunk.

share|improve this answer
add comment

Your Answer


