Replacing C++ virtual functions with managed code via GetFunctionPointerForDelegate RRS feed

  • Question

  • MY QUESTION:How do I replace a C++ function pointer with a function pointer to a managed function?
    POSSIBLE PITFALL: Managed code is running on a thread separate from the hosted CLR

    I am able to call member functions just fine using existing code which invokes C++ virtual functions. This code uses GetDelegateForFunctionPointer, and works fine in every scenario I've tried it. The functions are MSVC generated and use the __thiscall calling convention.


    My project relies on hooking certain virtual functions by editing or completely replacing the VTable (Virtual Function table). I am able to obtain an unmanaged function pointer for a delegate I have created. When I write this function pointer to the appropriate place in the virtual function table and the target (unmanaged code) executes it, there is a crash.


    I should clarify: I am hosting the CLR in the remote process on thread 'A'. The unmanaged code comes across this function pointer on a different thread. Is this undefined / unsafe behavior? Must I host the CLR in the same thread as the unmanaged code?? I would think ExecuteInDefaultAppDomain would block...

    CLR-Hosting DLL


    RuntimeHostV2.cpp (MSoft code)
     hr = CorBindToRuntimeEx(
     pszVer,    // Runtime version
     pszFlavor,   // Flavor of the runtime to request
     0,    // Runtime startup flags
     CLSID_CLRRuntimeHost,  // CLSID of ICorRuntimeHost
     IID_PPV_ARGS(&pClrRuntimeHost) // Return ICLRRuntimeHost
     hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(pszAssemblyName, 
     pszClassName, pszStaticMethodName, pszStringArg, &dwLengthRet);


    I call the export in a new thread:

        HRESULT hr = pExecute(L"MainLib.MainLib", L"Main", L"args", L"path\\to\\CSClassLibrary.dll"); //CSClassLibrary is a C# Class library that I would like to load & execute MainLib.MainLib.Main(args);


    New Function:
    public static int FSN(IntPtr thisobj)
     return 1;
      var deleg = new VEngine.NativeDelegate(FSN);
      var fp = Marshal.GetFunctionPointerForDelegate(deleg);
      //unsafe code to unprotect memory & overwrite function pointer


    Wednesday, March 23, 2011 10:50 PM


  • Hi syntroniks,


    Welcome to the MSDN forum!


    I suggest you to host CLR in the same thread but different AppDomains. If you do this, it doesn’t mean that the managed code will turns to be unmanaged. It is still managed code, and objects will be created in GC heap. It is complex to pass data or message between two threads.


    Have a nice day!

    Paul Zhou [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Paul Zhou Thursday, March 31, 2011 6:21 AM
    Tuesday, March 29, 2011 5:39 AM