Saturday, October 01, 2005

How to call C or C++ DLL in C#

You can call functions in a dll using the following simple method

1) you must know the function prototype (name of the function and its parameters and its return type).
2) in your code use a code like the following where DllImport Specfies the dll where the function exists and the line under it specifies the function prototype.

using System.Runtime.InteropServices;
namespace myNameSpace
{
public class MyClass
{
[DllImport("DLLPath.DLL")]
public static extern int FunctionName(int Argument1, bool Argument2);
}
}

an Example for using DllImport is to use a Windows API function

we will call a a function that can make you copy a file, its name is CopyFile and it is loacted in Kernel32.dll

this code sample demonstrate how to call this function

using System.Runtime.InteropServices;
namespace FileSystemClasses
{
public class FileSystem
{
[DllImport("Kernel32.DLL")]
public static extern bool CopyFile(string strSourcePath, string strTargetPath, bool bOverwrite);

public void TestDll()
{
FileSystem.CopyFile("c:\\a.txt", "c:\\b.txt", true);
}
}
}

there are other options that can be used with DllImport directive which gives some advanced options and more control which can be explained in another article

For a list of Windows API Functions according to their usage go to:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sdk
intro/sdkintro/contents_of_the_platform_sdk.asp

No comments: