jump to navigation

Using C++ DLL in ASP.NET (C#) February 27, 2008

Posted by Sabs in Technology.
14 comments

In my places in our program we have to use DLLImport, but it only works if the DLL is loaded. In windows application you can simply overcome this by placing the DLL in a designated folder, but in case of an ASP.NET application the code is compiled in an location which can’t be determined previously. It’s usually accessed from system32 ASP.NET folder and from a file created dynamically having some random naming. In .NET 1.1 the dynamic loading of dll using relflection was an available option, which we can also follow in ASP.NET 2.0 (see here) but we now also have another. We can load the DLL by calling Loadlibrary and then dll will be available to us in the memory and we can use it as we want.

Declaration of LoadLibrary in C#

[DllImport(“kernel32.dll”)]
static extern IntPtr LoadLibrary(string lpFileName);

[DllImport(“kernel32.dll”)]
public static extern IntPtr FreeLibrary(IntPtr library);
// This is a sample Dll, whose function Function1 is required for us in the application.

[DllImport(“Sample.dll”, EntryPoint = “Function1”)]
public static extern void Function1(Byte[] inStr, Byte[] outStr, long in_Len);

The use of LoadLibrary in C#

// The physical path of the DLL

string DLLPath = HttpContext.Current.Request.PhysicalApplicationPath + “\References\Sample.dll”;
//Call LoadLibrary
IntPtr lib = LoadLibrary(DLLPath); // If the lib is zero, the code has failed

// Use the declared function, if required or any other stuff
Function1(System.Text.ASCIIEncoding.Unicode.GetBytes(Password.Text),
pwd, Password.Text.Length*2);
Don’t forget to free it

FreeLibrary(lib); // Check HRESULT, if that bothers you

Please do send me any enhancements, updates or suggestions regarding the above mentioned post.

Advertisements