【问题标题】:Doing memcpy on my own?自己做memcpy?
【发布时间】:2018-05-06 13:01:57
【问题描述】:

所以,我想知道为什么我不能自己做 memcpy。这是有效的代码,可以让我得到正确的结果:

unsigned int VTableAddress = FindPattern( VTABLE_PATTERN, VTABLE_MASK );

unsigned int *p_VTable = NULL;

WriteMemory( &p_VTable, ( void* ) ( VTableAddress + 2 ), 4 );

//....

void D3DX9Interface::WriteMemory( void *address, void *bytes, int byteSize )
{
    DWORD NewProtection;

    VirtualProtect( address, byteSize, PAGE_EXECUTE_READWRITE, &NewProtection );
    memcpy( address, bytes, byteSize );
    VirtualProtect( address, byteSize, NewProtection, &NewProtection );
}

所以据我了解,WriteMemory 基本上将读/写保护设置为内存地址,然后简单地将字节复制到地址中。为了了解事情是如何工作的,我自己尝试了这段代码:

//Get the address of the vtable
unsigned int VTableAddress = FindPattern( VTABLE_PATTERN, VTABLE_MASK );

unsigned int *p_VTable = NULL;

CopyWithRWPrivileges( p_VTable, (unsigned int*)( VTableAddress + 2 ) );

//...

void D3DX9Interface::CopyWithRWPrivileges( unsigned int *p_Destination, unsigned int *p_Source )
{
    DWORD Protection( 0 );

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, PAGE_EXECUTE_READWRITE, &Protection );

    p_Destination = p_Source;

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, Protection, &Protection );
}

但由于某种原因,最后的代码给了我一个 NULL 指针。但为什么?

【问题讨论】:

  • p_Destination = p_Source; 不是复制操作。它重新分配本地指针p_Destination(在函数外不可见)
  • 谢谢!好的,明白了。但是当像 "unsigned int *&p_Destination" 这样传递 p_VTable 时,它​​仍然给我与 memcpy 不同的结果。

标签: c++ winapi memcpy


【解决方案1】:

好的,在 UnholySheep 的帮助下,我找到了解决问题的方法。所以首先,指针被复制而不是作为引用指针传递。其次,p_Source 也需要作为指针处理,因此使用此代码可以正常工作:

void D3DX9Interface::CopyWithRWPrivileges( unsigned int *&p_Destination, unsigned int *p_Source )
{
    DWORD Protection( 0 );

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, PAGE_EXECUTE_READWRITE, &Protection );

    p_Destination = *(unsigned int**) p_Source;

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, Protection, &Protection );
}

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多