Creating a cross-process function pointer

I have a Visual Studio 2008 C ++ project for Windows Mobile 6 with two processes. Both of which I would like to have access to the same function that is contained in process1.

This function Buzz:

struct TEST_STRUCT
{
    int bar;
    WCHAR foo[ 20 ];
};

typedef int( *pfn_Buzz )( TEST_STRUCT* );

int Buzz( TEST_STRUCT* info );

Process1 contains a definition for Buzzand creates a function pointer for it in a memory-mapped file:

int Buzz( TEST_STRUCT* info )
{
    info->bar = 1;
    wsprintf( info->foo, L"Hello!" );
    return 100;
}

int _tmain( int argc, _TCHAR* argv[] )
{
    // create a memory-mapped file shared memory space that can be read by any process
    HANDLE mapping = ::CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof( pfn_Buzz ) , NULL );
    LPVOID buzz_addr = ::MapViewOfFile( mapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof( pfn_Buzz ) );

    // find our process' memory offset
    DWORD offset = ::GetCurrentProcessIndex() + 0x02000000;

    // copy the complete function address to the shared memory space
    buzz_addr = ( LPVOID )( ( DWORD )&Buzz + offset );

    // convert the function address to a string to send to process2.exe
    WCHAR address[ 9 ] = { 0 };
    wsprintf( address, L"%x", ( ( DWORD )buzz_addr ) );

    // start process2.exe and wait for it to finish
    PROCESS_INFORMATION pi = { 0 };
    ::CreateProcess( L"\\test_user.exe", address, NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi );
    ::WaitForSingleObject( pi.hProcess, INFINITE );

    ::UnmapViewOfFile( buzz_addr );
    ::CloseHandle( mapping );

    return 0;
}

Process2 receives the address Buzzfrom Process1, sends it to the function pointer pfn_Buzzand executes it.

// process2.exe
int _tmain( int argc, _TCHAR* argv[] )
{
    // get the address of the Buzz() function pointer
    WCHAR* wszAddr = argv[ 1 ];
    WCHAR* wszAddrEnd = &argv[ 1 ][ 8 ];
    DWORD address = wcstol( wszAddr, &wszAddrEnd, 16 );
    pfn_Buzz PFNBuzz = ( pfn_Buzz )address;

    // execute buzz
    TEST_STRUCT test = { 0 };
    PFNBuzz( &test );

    return 0;
}

Unfortunately, I get an Illegal Instruction exception in process2 when I try to execute a function PFNBuzz.

Can anyone suggest what I can change to get the functionality I need?

Thanks PaulH

+3
3

, , DLL DLL . , , "", .

/ , , .

Visual ++ __based, .

+2

- , A ( B) 2 . Process A, , , , , . .

, Inter-Process Communication (IPC).

IPC . , . , , A Process B, . , , . , , .

, IPC , , , - Remote Procedure Call (RPC).

, , RPC. DCOM Corba. Raknet - , RPC. . . , , :)

+5

__declspec(dllexport), GetProcAddress(), . ++ extern "C" , . :

extern "C" int __declspec(dllexport) Buzz( TEST_STRUCT* info ) { ... }
int main ( int, char ** )
{
    pfn_Buzz buzz = GetProcAddress(GetModuleHandle(NULL), "Buzz");
    // ...
}

, IPC .

+2

Source: https://habr.com/ru/post/1772948/


All Articles