public void ResolveImports() { int numImports = 0; foreach (var import in Imports) { var hModule = Win32.LoadLibrary(import.ModuleName); if (hModule == IntPtr.Zero) { throw new Exception(String.Format("Module load failed: {0}", import.ModuleName)); } try { var procAddress = Win32.GetProcAddress(hModule, import.FunctionName); if (procAddress == 0) { throw new Exception(String.Format("Unresolved import: {0}:{1}", import.ModuleName, import.FunctionName)); } var section = SectionFromVirtualAddress(import.FunctionAddressDestination); var offset = import.FunctionAddressDestination - section.VirtualAddress; var bytes = BitConverter.GetBytes(procAddress); Array.Copy(bytes, 0, section.RawData, offset, bytes.Length); numImports += 1; } finally { Win32.FreeLibrary(hModule); } } }
protected IntPtr GetFunctionAddress(string moduleName, string functionName) { var hModule = Win32.LoadLibrary(moduleName); if (hModule == IntPtr.Zero) { throw new Exception(String.Format("Module load failed: {0}", moduleName)); } try { var procAddress = new IntPtr(Win32.GetProcAddress(hModule, functionName)); if (procAddress == IntPtr.Zero) { throw new FunctionNotExportedException(moduleName, functionName); } return(procAddress); } finally { Win32.FreeLibrary(hModule); } }