简体   繁体   中英

Passing C# array of COM objects to VB6

I'm trying to pass .NET array to COM VB6 library. I have an object which is COM wrapper of VB6 object. It has method with the following signature:

[MethodImpl(MethodImplOptions.InternalCall, 
    MethodCodeType = MethodCodeType.Runtime)]
void AddEx([MarshalAs(UnmanagedType.Struct)] object vSafeArrayOfItems);

but when I call it I get an ArgumentException with the following message:

Value does not fall within the expected range.

The type of exception and its description doesn't even depend on passed element.

Does anybody know how to go around this issue?

UPD: I removed .NET wrapper assemblies and referrenced source .COM libraries. No changes had happened.

I think you could write the external method declaration like the following:

[DllImport...
public static extern void AddEx(YourType[] paramName);

//or like the following:

public static extern unsafe void AddEx(YourType * paramName);

You would need to mirror the VB6 struct format:

[StructLayout(LayoutKind.Sequential)]
public struct myStruct {
    type1 member1;
    type2 member2;
}

To import the function you would have to do:

[DllImport("dllname.dll")]
public static extern void AddEx(IntPtr paramName);

You can easily use the following functions to perform struct <-> IntPtr conversions:

myStruct struct = Marshal.PtrToStructure(paramName, typeof(myStruct));
// do stuff
Marshal.StructureToPtr(struct, paramName, false);

Edit: I misread what you wanted to do. But this is a starter for doing the interop.

The argument exception comes from trying to send a reference type as a value type. (object is a class, structs are handled differently)

If you want to pass an array you would do:

void AddEx([MarshalAs(UnmanagedType.LPArray)] ref myStruct[] param);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM