Tuesday 8 February 2011

APIs (Application Programming Interface

APIs (Application Programming Interface) are used in many higher level programming languages to directly make a call to a function inside a DLL (Dynamic Linked Library) which was designed in C++. APIs increase the efficiency of programs that use algorithms with many mathematical computations.

Syntax

When declaring APIs in C#, use the following syntax:

using System.Runtime.InteropServices;

...

[DllImport( dll_filename )]
[public|private] static extern ret_type function( [type para, ...] );

Example

Making a program that uses the Windows API PlaySound. The following example demonstrates how to implement the Windows API PlaySound in a C# application. Notice that the API is declared inside the class clsAPI.

using System;
using System.Runtime.InteropServices;

namespace APITest
{
class clsAPI
{
[DllImport("winmm.dll")]
public static extern long PlaySound(string lpszName, long hModule, long dwFlags);

[STAThread]
static void Main(string[] args)
{
long retval;
string fname = "e:\\sounds\\hit.wav";

retval = PlaySound( fname, 0, 1 );
}
}
}

Where to Find APIs

A list of all the Windows APIs can be found in the API Text Viewer that comes with Visual Studio 6. The C++ .NET documentation provides help on how to use each API function.


No comments:

Post a Comment