Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the function LoadLibrary from kernel32.dll returns zero in Asp web application

Tags:

c#

asp.net

I'am going to use a kernel32 dll in asp.net web application. This is the code: //DllGetClassObject function pointer signature private delegate int DllGetClassObject(ref Guid ClassId, ref Guid InterfaceId, [Out, MarshalAs(UnmanagedType.Interface)] out object ppunk);

//Some win32 methods to load\unload dlls and get a function pointer
private class Win32NativeMethods
{
  [DllImport("kernel32.dll", CharSet=CharSet.Ansi)]
  public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);

  [DllImport("kernel32.dll")]
  public static extern bool FreeLibrary(IntPtr hModule);

  [DllImport("kernel32.dll")]
  public static extern IntPtr LoadLibrary(string lpFileName);
}
public string GetTheDllHandle (dllName)
{
    IntPtr dllHandle = Win32NativeMethods.LoadLibrary(dllName); // the dllHandle=IntPtr.Zero
    return dllHandle.ToString();
}

The problem that when I call my function GetTheDllHandle, the dllHandle return zero

Did anybody out there made something similar? Or does anybody have any suggestions?

like image 908
Dhibi_Mohanned Avatar asked Mar 13 '14 15:03

Dhibi_Mohanned


1 Answers

Returning 0 while loading DLLs is coming due to several reasons like , DLL is not there on specified path or DLLs is not supported with platform or dependent dlls are not loaded before you build your native DLL. so you can track these errors by set true for SetLastError property

DllImport("kernel32.dll", EntryPoint = "LoadLibrary", SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
public string GetTheDllHandle (dllName)
{
   IntPtr dllHandle = Win32NativeMethods.LoadLibrary(dllName); // the dllHandle=IntPtr.Zero

   if (dllHandle == IntPtr.Zero)
      return Marshal.GetLastWin32Error().ToString(); // Error Code while loading DLL
   else
      return dllHandle.ToString();  // Loading done !
}
like image 163
Mohsin khan Avatar answered Sep 22 '22 16:09

Mohsin khan