Groups | Blog | Home
all groups > dotnet interop > december 2006 >

dotnet interop : expose .NET component through COM and events


Tomasz Grobelny
12/4/2006 5:54:19 PM
I want to write .NET component and use it in my legacy C++ application.
All works fine but somehow event handling does not work as expected. The
C# code is as follows:
using System;
using System.Runtime.InteropServices;

namespace Bank
{
// Interface to allow COM clients to use events.
// Define it as a pure dispatch interface
[
Guid("ef81a831-fa49-4ede-b70b-08f2e9d602b2"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)
]
public interface IAccountEvents {
[DispId(1)]
void NewRate();
}

public interface IAccount
{
double Rate { get; }
int SetRate(double d);
}

// Delegate for rate change event
[ComVisible(false)]
public delegate void RateDelegate();

// Export the Account class, exposing IAccountEvents
// as a source interface
[ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(IAccountEvents))]
public class Account : IAccount {
private static double interestRate = 0;

// Define the event
public event RateDelegate NewRate;

public Account() {
}

public double Rate {
get {
return interestRate;
}
}

// Fire the event
public int SetRate(double d) {
Console.WriteLine("Set Rate");
Console.Out.Flush();
NewRate();
return 42;
}
}
}

And the C++ code looks like this:

BEGIN_DISPATCH_MAP(CIEComCtrlSink, CCmdTarget)
DISP_FUNCTION_ID(CIEComCtrlSink, "NewRate",1,NewRate,VT_EMPTY,
VTS_NONE) //not sure if this "1" is correct
END_DISPATCH_MAP()

BOOL CIEComCtrlSink::MyAdviseSink()
{
HRESULT hr=account.CreateInstance(Account::CLSID_Account);
if(!SUCCEEDED(hr))
{
CString strMsg;
strMsg.Format("Failed to create object error = 0x%x",(int)hr);
AfxMessageBox(strMsg);
return false;
}

// advise the browser to send events here
LPUNKNOWN pUnkSink = GetIDispatch(FALSE);
AfxConnectionAdvise((LPUNKNOWN)account,Account::DIID_IAccountEvents,pUnkSink,FALSE,&m_dwCookie);

double rate;
account->get_Rate(&rate);
account->SetRate(2.5);

return TRUE;
}

Thanks in advance for any help (showing where I made a mistake, links to
working samples, etc.),
--
Regards,
Tomasz Grobelny
12/4/2006 8:33:44 PM
[quoted text, click to view]
Of course I didn't write where it fails...

[quoted text, click to view]
This function returns 0...

[quoted text, click to view]
....and this one causes abnormal program termination. Propably because the
NewRate event isn't handled properly.

[quoted text, click to view]
--
Regards,
AddThis Social Bookmark Button