将LPVOID转换为struct

时间:2014-10-12 19:11:34

标签: c# c++ casting

我想通过CreateRemoteThread读取我在另一个进程中注入的DLL的参数。

我可以毫无问题地调用该函数,我只是不知道如何将LPVOID转换为结构。

这是一个例子:

#pragma pack(push,1)
struct tagRemoteThreadParams
{
    int Param1;
    int Param2;
} RemoteThreadParams, *PRemoteThreadParams;
#pragma pack(pop)

DWORD WINAPI testfunction(LPVOID param)
{
    // cast LPVOID to tagRemoteThreadParams (param)
    WriteToLog("YES YOU CALLED THE FUNCTION WITH PARAM: ");
    return 0;
}

这是我的结构以及我如何在进程中分配mem:

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct RemoteThreadParams
{
    [MarshalAs(UnmanagedType.I4)]
    public int Param1;

    [MarshalAs(UnmanagedType.I4)]
    public int Param2;
}

public uint CallFunction(int _arg1)
{
    RemoteThreadParams arguments = new RemoteThreadParams();
    arguments.Param1 = 1;
    arguments.Param2 = 2;

    //pointer to the function im trying to call
    IntPtr _functionPtr = IntPtr.Add(this.modulePtr, 69772);

    // Allocate some native heap memory in your process big enough to store the
    // parameter data
    IntPtr iptrtoparams = Marshal.AllocHGlobal(Marshal.SizeOf(arguments));

    // Copies the data in your structure into the native heap memory just allocated
    Marshal.StructureToPtr(arguments, iptrtoparams, false);

    //allocate som mem in remote process
    IntPtr lpAddress = VirtualAllocEx(this.processHandle, IntPtr.Zero, (IntPtr)Marshal.SizeOf(arguments), AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite);

    if (lpAddress == IntPtr.Zero)
    {
        return 0;
    }

    if (WriteProcessMemory(this.processHandle, lpAddress, iptrtoparams, (uint)Marshal.SizeOf(arguments), 0) == 0)
    {
        return 0;
    }
    //Free up memory
    Marshal.FreeHGlobal(iptrtoparams);

    uint threadID = 0;
    IntPtr hThread = CreateRemoteThread(this.processHandle, IntPtr.Zero, 0, _functionPtr, lpAddress, 0, out threadID);
    if (hThread == IntPtr.Zero)
    {
        //throw new ApplicationException(Marshal.GetLastWin32Error().ToString());
        throw new Win32Exception();
    }
    WaitForSingleObject(hThread, 0xFFFFFFFF);
    // wait for thread to exit


    // get the thread exit code
    uint exitCode = 0;
    GetExitCodeThread(hThread, out exitCode);

    // close thread handle
    CloseHandle(hThread);

    return exitCode;
}

2 个答案:

答案 0 :(得分:0)

如果我正确理解你的代码,你将UT8编码的字符串注入到另一个进程内存中(我很惊讶它的工作原理)。

假设它确实有效,在C ++代码中,您需要将param指向的UTF8编码字节数组转换为C ++理解的某种字符串。

一种方法是使用MultiByteToWideChar

另一种方法是使用STL。我发现了一个关于它的问题here

答案 1 :(得分:0)

演员问题的答案是:

struct tagRemoteThreadParams *tData = (struct tagRemoteThreadParams *)param;

感谢帮助人员