【发布时间】:2014-06-21 13:53:26
【问题描述】:
我正在尝试使用 Interop 将 .dll 注入另一个进程的内存。
这是我的 C# 代码:
class Program
{
static void Main(string[] args)
{
var result = Inject(Process.GetProcessesByName("notepad")[0].Id);
Console.WriteLine(result);
if (result < 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
Console.ReadLine();
}
[DllImport("Testing.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Inject(int dwProcessId);
}
函数Inject的代码是这样的(注意return -6上的注释):
//C++ .dll that does actually exists
const char* DLL_NAME = "C:\\Users\\Bruno\\Source\\Repos\\CourseGuidance\\InteropTesting\Debug\\Loader.dll";
TESTING_API DWORD Inject(DWORD dwProcessId)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
if (hProcess == NULL)
return -1;
HMODULE hModule = GetModuleHandleW(L"kernel32.dll");
if (hModule == NULL)
return -2;
FARPROC pLoadLibrary = GetProcAddress(hModule, "LoadLibraryA");
if (pLoadLibrary == NULL)
return -3;
LPVOID pMemory = VirtualAllocEx(hProcess, NULL, strlen(DLL_NAME) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (pMemory == NULL)
return -4;
BOOL result = WriteProcessMemory(hProcess, pMemory, DLL_NAME, strlen(DLL_NAME) + 1, NULL);
if (!result)
return -5;
HANDLE hThread = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE) pLoadLibrary, pMemory, 0, NULL);
if (hThread == NULL)
return -6;
WaitForSingleObject(hThread, INFINITE);
VirtualFreeEx(hProcess, pMemory, strlen(DLL_NAME) + 1, MEM_RELEASE);
CloseHandle(hThread);
CloseHandle(hProcess);
return 0;
}
我认为我得到的错误可能具有误导性,因为该文件确实存在于该文件夹中。我还认为错误可能是因为LoadLibraryA,它是用于ASCII,甚至尝试使用LoadLibraryW,但我仍然遇到同样的问题。
如果有人知道可能出了什么问题,你能给我提供正确的方向吗?
【问题讨论】:
-
实际错误是什么?十六进制错误代码?会不会是依赖问题,DLL依赖于其他找不到的模块?
-
实际代码为
2 -
你有一个标准的一对一错误,在 C 字符串中很常见。您忘记复制 0 终止符。请改用
strlen(DLL_NAME) + 1。 -
在您的 const char* DLL_NAME 中,其中一个反斜杠没有加倍。
-
您为什么不告诉我们 Inject 函数返回什么值?
标签: c# visual-c++ dll-injection createremotethread