none
Using com interop to pass a structure from unmanaged code to managed code. RRS feed

  • Question

  • I want a legacy MFC application to interact with a C# dll.

    On the managed side I have something like:

    	[ComVisible(true)]
    	[StructLayout(LayoutKind.Sequential)]
    	public struct MyStruct
    	{
    		public int data1;
    		public bool someFlag;
    		public double syringeSize;
    	}
    
    	[ComVisible(true)]
    	public class MyClass
    	{
    		public void Set(MyStruct structure, int index)
    		{
    		}
    	}
    

    Using regasm I create the type library file and import that in to the MFC application by using the "MFC class from TypeLib" wizard template in VS 2011, the structure appears in the tlh file but when I try to call the generated IDispatch wrapper class created by the wizard:

    	void Set(MyStruct structure, long index)
    	{
    		static BYTE parms[] = VTS_UNKNOWN VTS_I4 ;
    		InvokeHelper(0x60020008, DISPATCH_METHOD, VT_EMPTY, NULL, parms, structure, index);
    	}
    

    It fails with COleException E_INVALIDARG, I am not using any pointers strings or anything particularly difficult and yet the interop tools seem unable to deal with a structure.

    I would like to pass an array of structures but CComSafeArray seems only to work for defined types not UDT's unless you create a SAFEARRAY and attach it to the template, but at the very least I would like to pass a structure.

    I can call other functions in my managed library as long as they use defined types.

    Thank you.

    Sunday, July 14, 2013 11:17 PM

Answers

  • Well I do not know why the generated code did not work and I do not know how to pass a structure in this manner but I did make a workaround. Instead of trying to pass a structure I pass a class.

    	[ComVisible(true)]
    	[StructLayout(LayoutKind.Sequential)]
    	public class MyStruct
    	{
    		public int data1;
    		public bool someFlag;
    		public double syringeSize;
    	}
    
    
    Regasm generates get and put functions for the variables, I have to create and manage the resulting COleDispatchDriver class but at least I can transfer my data.
    • Marked as answer by ellipsisware Friday, July 19, 2013 6:01 PM
    Monday, July 15, 2013 8:15 PM