Registering _set_purecall_handler function using P/Invoke in C#

家住魔仙堡 提交于 2019-12-11 13:09:48

问题


I'm having trouble using _set_purecall_handler with P/Invoke in C#.

Basically, this works:

(C++)

_set_purecall_handler(MyPureCallHandler);

void MyPureCallHandler(void)
{
    // gets called
}

But this doesn’t:

(C#)

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void PureCallHandler();

[DllImport("msvcr100.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _set_purecall_handler([MarshalAs(UnmanagedType.FunctionPtr)] PureCallHandler handler);

_set_purecall_handler(MyPureCallHandler);

private void MyPureCallHandler()
{
    // *** doesn’t get called ***
}

I’m not sure if my P/Invoke method signature is correct, but it doesn't throw any errors when I call the function (it just doesn't fire the callback on a pure virtual call error).

Background

We have a number of apps (C++, C++/CLI and C#) that use a single C# library for catching exceptions. This registers various handlers (AppDomain.CurrentDomain.UnhandledException, SetUnhandledExceptionFilter, etc) and catches most exceptions.

However, it doesn't catch pure virtual call errors and so we need to register the above function.


回答1:


After trial and error, I found that referencing msvcr100d.dll (d = debug) instead of msvcr100.dll worked as I was under the debugger.

Here's my source (I don't know if this is good practice, but I've successfully tested under debug / release mode):

private const string DllName =
    #if DEBUG
        "msvcr100d.dll";
    #else
        "msvcr100.dll"; 
    #endif

public delegate void PureCallHandler();

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern PureCallHandler _set_purecall_handler(PureCallHandler handler);


来源:https://stackoverflow.com/questions/11649401/registering-set-purecall-handler-function-using-p-invoke-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!