Use a C library from C# code

27,505

C Libraries compiled for Windows can be called from C# using Platform Invoke.

From MSDN, the syntax of making a C function call is as follows:

[DllImport("Kernel32.dll", SetLastError=true)]
static extern Boolean Beep(UInt32 frequency, UInt32 duration);

The above calls the function Beep in Kernel32.dll, passing in the arguments frequency and duration. More complex calls are possible passing in structs and pointers to arrays, return values etc...

You will need to ensure that the C functions available by the C library are exported appropriately, e.g. the Beep function is likely declared like this:

#define DllExport   __declspec( dllexport )
DllExport bool Beep(unsigned int frequency, unsigned int duration)
{
    // C Body of Beep function
}
Share:
27,505
murmansk
Author by

murmansk

Developer in C#, XAML technology including WPF, Windows Phone, Windows Universal App

Updated on June 06, 2020

Comments

  • murmansk
    murmansk almost 4 years

    I have a library in C-language. is it possible to use it in C sharp.

    http://zbar.sourceforge.net/ is the link of library i want to use