开发者

Problem with triggering Events in a .NET DLL via COM from Delphi

i have a problem with COM objects and triggering events. I have:

  • a DLL written in C#.NET (3.5), which triggers events
  • a开发者_StackOverflow社区n application in Delphi5, which uses the DLL as a COM object.

So far so good. Events go like this: - in the DLL there are 2 events. One is internal and is not COM-visible. The second one is external and is visible by COM - there is also a OnChanged function in the DLL, which is connected to the internal event and triggers the external event. So basically everytime the internal event is trigger, so is the external event. - this OnChanged function is also COM-visible and can be called from the Delphi app

I used this solution to get the whole thing working, I can successfully bind a Delphi procedure to the .NET event, but there's a catch: - if I call OnChanged from the Delphi app, everything's peachy - the binded Delphi function will get executed as well as (obviously) the .NET function - if the DLL calls OnChanged from a callback function in .NET, the binded Delphi function will NOT get executed.

Bottomline: if I trigger the external event from Delphi, everything is OK. If the DLL triggers the internal event, nothing will happen in Delphi (although for sure the external event is triggered).

Any ideas are highly appreciated!


It's very hard to answer this without debugging the actual code but I will tell you about one problem I have encountered in the past with COM interop.

One possibility that you might want to entertain is that the event hookup is getting released by the GC. When you attach to an event on a object that event will usually take a reference out on the attacher and both objects will not get cleaned up by the GC but when you have a COM object the GC doesn't necessarily know about that reference and it can clean up one of the objects. I have encountered this in the past with Office automation via .net. The way to solve this is to keep the reference to the COM object and attach to it.

For example this is bad:

public class Foo
{
  public Foo(ICOMObject obj)
  {
    obj.Changed += OnChanged;
  }

  private void OnChanged(object arg)
  {
  }
}

This will work just fine if obj is a .net object. The event will remain hooked up as long as one of the objects remains referenced. However this will not work with a COM object. With a COM object, the event will appear to just stop working at some point in time, usually rather quickly.

Instead try this:

public class Foo
{
  ICOMObject obj;
  public Foo(ICOMObject obj)
  {
    this.obj = obj;
    this.obj.Changed += OnChanged;
  }

  private void OnChanged(object arg)
  {
  }
}

I'm not sure that this is your problem but it might be. Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜