C# - LoadLibrary fails with 32bit DLL - c#

I've got a C# application which loads a DLL at runtime. The DLL is 32bit, so it is the application.
I tried with the LoadLibrary from:
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
private static extern bool FreeLibrary(IntPtr hModule);
but without result; it always return IntPtr.Zero. I tried also using
[DllImport("%windir%\\SysWOW64\\kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("%windir%\\SysWOW64\\kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("%windir%\\SysWOW64\\kernel32.dll")]
private static extern bool FreeLibrary(IntPtr hModule);
but this way the application gets a "System.Windows.Markup.XamlParseException" exception when calling LoadLibrary.
Did anyone met this issue before?

Your C# exe have to be compiled to 32bit.
Check this page for error code detail:
https://msdn.microsoft.com/en-us/library/ms681382(v=vs.85).aspx
ERROR_BAD_EXE_FORMAT
193 (0xC1)
%1 is not a valid Win32 application.

Related

Memory Management of imported C++ methods in C#

I have a Windows Forms Application that imports and uses some C++ methods from user32.dll.
[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(int xPoirnt, int yPoint);
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(String sClassName, String sAppName);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr parentHandel, IntPtr childAfter, String sClassName, String windowTitle);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
[DllImport("msvcrt.dll")]
private static extern int memcmp(IntPtr b1, IntPtr b2, long count);
I've noticed that after my app runs for an extended period of time, the memory usage can go up to 500~MB (initial 5MB).
I don't have that much C++ experience but I know that you have to manually do memory management for C++.
My questions is, do I have to do memory management for my app or will the C# garbage collector handle it.

EasyHook LoadLibrary fails in crash

I am trying to use EasyHook to detect native LoadLibrary calls.
It indeed detects the loading of libraries, however the process results in freezing.
This is because the LoadLibrary_Hook method below cannot load the dll or library since It returns 0 IntPtr (Probably can't find the library.).
I even tried setting the events to a "void" type but then the process simply crashes, this is probably because EasyHook expects me to return a value to overwrite the function.
Is there a way for me to return the exactly needed library to be loaded, or just simply get the name of the library that is being loaded without me having to load the library manually?
(There are also names like this which are loading in the process: 瑮汤⹬汤l邐邐讐嗿謘ౕ㍓四襗ﱝ嶉觬嶉觰嶉㯨࿓トă謀ࡅ쌻萏Ͽ䶋㬔瓋㤉ᡝ萏ϯ팻Ѵ᪉ᢉ疋㬐࿳ă㬀瓋謇ᡅᦉᢉ綋㬜 which is kinda odd...)
private static LocalHook hook;
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
public static extern IntPtr GetProcAddress(IntPtr handle, string varormethodname);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
public delegate IntPtr LoadLibraryDelegate(string lpFileName);
public TestHook()
{
IntPtr kernel32 = GetModuleHandle("kernel32.dll");
Logger.Log("Kernel: " + kernel32);
IntPtr address = GetProcAddress(kernel32, "LoadLibraryA");
Logger.Log("Address: " + address);
hook = LocalHook.Create(address,
new LoadLibraryDelegate(LoadLibrary_Hook),
null);
hook.ThreadACL.SetExclusiveACL(new Int32[] {0});
//RemoteHooking.WakeUpProcess();
}
public IntPtr LoadLibrary_Hook(string lpFileName)
{
Logger.Log("File load: " + lpFileName);
return LoadLibrary(lpFileName);
}
Solution was to call the original method using the original function address:
public IntPtr LoadLibrary_Hook(string lpFileName)
{
Logger.Log("File load: " + lpFileName);
LoadLibraryDelegate origMethod = (LoadLibraryDelegate)Marshal.GetDelegateForFunctionPointer(LoadLibraryAddress, typeof(LoadLibraryDelegate));
return origMethod(lpFileName);
}

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

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?
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 !
}

FindWindow return 0 in Windows 7

I have a C# program. The program creates an Adobe Reader process and prints a PDF document. It works fine in Windows XP, but does not work in Windows 7. I have checked that the AcroRd32.exe path is correct in Windows 7. The FindWindow method always returns 0 in Windows 7.
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("User32.dll")]
public static extern IntPtr FindWindow(string ClassN, string WindN);
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("shell32.dll ")]
public static extern int ShellExecute(IntPtr hwnd, string lpszOp, string lpszFile, string lpszParams, string lpszDir, int FsShowCmd);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern uint WinExec(string lpCmdLine, uint uCmdShow);
public bool isAcrobatExsists(string acrobatLoc)
{
IntPtr currentHandle = getWindowHandlerByClass("AcrobatSDIWindow");
if (currentHandle != IntPtr.Zero)
{
return true;
}
return false;
}
private static IntPtr getWindowHandlerByClass(string className)
{
IntPtr currentHandle = FindWindow(className, null);
return currentHandle;
}
private static IntPtr getWindowHandlerByName(string appName)
{
IntPtr currentHandle = FindWindow(null, appName);
return currentHandle;
}
Findwindow can depend a great deal on how you are running the application. It sounds like you might be running it as a scheduled task or a windows service. These run in a different session than what the user's desktop window is in, so it won't see or be able to interact with them.
They introduced this change in Windows Vista, so applications that do this will work just fine in XP but fail in Windows Vista or later.
Here's a link from msdn about it: Application Compatibility: Session 0 isolation

How to fix "invalid access to memory location" error?

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
static void Main(string[] args)
{
IntPtr handle = LoadLibrary(#"ItwNidSmart.dll");
if (handle == IntPtr.Zero)
{
try
{
int hr = Marshal.GetHRForLastWin32Error();
Marshal.ThrowExceptionForHR(hr);
}
catch (Exception ex)
{
Console.Write("Error: "+ ex.Message);
}
}
IntPtr proc = GetProcAddress(handle, "InitializeModule");
}
I try to load this native C++ library in my Windows 7 x64, but I got this error. I've already built this solution to x86 application.
The error occurs at the call to LoadLibrary().
You didn't actually state the exact error message, and which line it occurs on. Is it possible that you are erroneously linking to the 32 bit version of ItwNidSmart.dll?
In fact, your P/Invokes are wrong, which may or may not be the cause of your problem. The most important error is that GetProcAddress specifies the procedure name as an ANSI string. They should read:
[DllImport("kernel32", SetLastError=true)]
static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
static extern UIntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", SetLastError=true)]
static extern bool FreeLibrary(IntPtr hModule);
I'm not sure that these errors are actually causing you problems.
EDIT
You state in a comment that the failure occurs at the call to LoadLibrary(). If this raises an exception then the only explanation that I can come up with is that the fault lies in the DLLMain() of the DLL and not in the C# code. If the DLL was the wrong bitness, or not found, then LoadLibrary() would return NULL.
I think to solve this you need to look to the DLL and not the C# code.

Categories