tags:

views:

51

answers:

3

I have a COM method which returns a MFC CRect:

GetMFCRect(LONG* pRect)
*((CRect*)pRect) = m_currentRect;

In my .NET application I try the following:

int pointer = new int();
Rectangle rc;
IntPtr pIntResult;
unsafe
{
    int* p = &pointer;
    _COMobj.GetMFCRect(ref *p);
    pIntResult = new IntPtr(p);
    rc = (Rectangle)Marshal.PtrToStructure(pintResult, typeof(Rectangle));
}

But rc has the wrong values. What is wrong with this code?

Thanks!

A: 

The convertion from LONG* to CRect seems weird. A CRect contains 4 longs, are you treating it as an array or so? If GetMFCRect indeed hacks its way to the CRect, no wonder it's not compatible with .NET. If possible, I'd say get the COM method to accept a well defined structure which can be marshaled properly, without getting into alignment issues and so.

My guess is that in MFC this works because when working in-process, marshaling is not needed, and you share the same address space with the COM object. However, when called from .NET, marshaling is indeed required, and when a CRect is passed as a LONG*, it just can't be done properly.

eran
+1  A: 

AFAIK, Rectangle is a rather simple structure, and has no casting or conversion from CRect; what you see as values, there, are most probably pointers in the m_currentRect's VTable.
As a possible solution I would pass a GDI RECT structure, that is much safer, or directly the four coordinates.

Roberto Liffredo
A: 

Thanks! I will try to persuade the developer COM library that would change the method GetMFCRect