Monday, September 22, 2008

Invoke .NET from MFC(COM object - ActiveX)

Hi there...
A couple of days ago I wanted to use a .NET assembly from a MFC application. You can see other post where I explain how to make an interface in .NET and expose it to COM.

In this post I want to show you how to call a method from that assembly that has a byte[] parameter. and how to get a parameter from a COM object. As you can see(if you've made that .tbl file and imported in C++), the byte[] parameter from .NET is exposed as a SAFEARRAY*.
The trick is to create a SAFEARRAY* like this:
BYTE* myBuffer = ... ; // the length of the buffer is len
SAFEARRAYBOUND sabdBounds[1] = { {len, 0} };
LPSAFEARRAY psa = SafeArrayCreate(VT_UI1, 1, sabdBounds);
memcpy(psa->pvData, myBuffer, len);
//call the method from .NET assembly

To call a method or get a property from a COM object, you can use the InvokeHelper method:

//get signature BSTR string
VARIANT vtResult;
this->GetDlgItem(IDC_MyActiveXID)->InvokeHelper(propertyId, DISPATCH_PROPERTYGET

After this call, you should check on vtResult.vt to see the return type.

Have fun!

No comments: