[事先道歉。我已经在这里和codeproject.com上看了几个关于这个主题的帖子,但我还是遗漏了一些东西。]
我有一个通知框架(类似于Events),作为用非托管C ++编写的遗留系统的一部分。我还有一个混合模式DLL,托管类向托管世界公开遗留功能。
CacheControlNotification类是一个管理桥类,用于将未管理的事件转换为托管事件。它包含一个非托管的NativeCcmBridge类,它在旧框架中注册以接收非托管消息。 NativeCcmBridge将数据封送到托管类型,并将其传递到CacheControlNotification,然后将其发送给感兴趣的托管方。
GetDelegateForFunctionPointer()抛出NotSupportedException:代理不能从本机代码封送到其主域以外的域中。
回调发生在源自本机代码的线程中。这个例外让我相信我的解决方案存在根本缺陷。
感谢任何帮助。感谢。
罗伯特
public delegate void OnNotifyHandler ( ManagedCallbackMessage^ );
//
// Native class to marshal callback to managed code. Callbacks
// in the native world are registered via an "ANativeHandler" type.
//
class NativeCcmBridge : public ANativeHandler
{
private:
//
// Pointer to the managed delegate
//
IntPtr m_callbackPtr;
public:
NativeCcmBridge ( OnNotifyHandler^ callback )
{
m_callbackPtr = Marshal::GetFunctionPointerForDelegate(callback);
}
//
// Provide implementation for pure virtual native handler
//
virtual void OnNotify (NativeCallbackMsg& nativeCallbackMsg)
{
// Convert the native message to a managed message
ManagedCallbackMessage^ msg = new ManagedCallbackMessage( nativeCallbackMsg );
// Now push the managed message via the delegate
// throws NotSupportedException: Delegates cannot be marshaled from native code into a domain other than their home domain.
OnNotifyHandler^ callback = (OnNotifyHandler^)Marshal::GetDelegateForFunctionPointer(m_callbackPtr, OnNotifyHandler::typeid);
callback( msg );
}
};
//
// Managed Class to receive marshalled messages and
// reissue in managed world.
//
public ref class CacheControlNotification
{
public:
CacheControlNotification()
{
m_callback = (OnNotifyHandler^) Delegate::CreateDelegate( OnNotifyHandler::typeid, this, "RaiseNotification" );
m_bridge = new NativeCcmBridge( m_callback );
// Register m_bridge the native mechanism
}
virtual ~CacheControlNotification () { this->!CacheControlNotification(); }
!CacheControlNotification ()
{
delete m_bridge;
m_bridge = nullptr;
}
event OnNotifyHandler^ OnNotify;
protected:
NativeCcmBridge* m_bridge;
pin_ptr<OnNotifyHandler^> m_callback;
void RaiseNotification ( CacheControlMessage^ msg )
{
OnNotify( msg );
}
};