简体   繁体   中英

How pass an decimal from c# to vb6 with Interop

I have an interop c# class with a property:

decimal ImportoDocumento {  get; set; }

if i try to access to this property from vb6 a receive an error:

Compiler error: Function or interface marked as restricted or the function uses an automation type not supported in visual basic.

So i found this partial solution:

decimal ImportoDocumento { [return: MarshalAs(UnmanagedType.Currency)] get; [param: MarshalAs(UnmanagedType.Currency)] set; }

but currency supports numbers with max 4 decimals. i have numbers with 6 decimals too.

How can i do?

The error message is appropriate, decimal is not a valid interop type. It suffers from very poor standardization, the big chip bakers like Intel and AMD don't want to touch it with a ten foot pole. I can't remember VB6 anymore but this MSDN article brings the point home well:

At this time the Decimal data type can only be used within a Variant, that is, you cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal using the CDec function.

You declare a property as a variant by changing its type to object . I know that the .NET Decimal type is in fact compatible with the VB6 and VBA variant type, it is baked into oleauto.dll which is used both by the CLR and the VB6 and VBA runtime. Fix:

[ComVisible(true)]
public interface IExample {
    object ImportoDocumento { get; set; }
}

[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class Example : IExample {
    private decimal documento;
    public object ImportoDocumento {
        get { return documento; }
        set { documento = Convert.ToDecimal(value, null); }
    }
}

Note that you can play with the IFormatProvider argument of Convert.ToDecimal(). Matters when the VB6 code is apt to assign a string, not uncommon. You might also consider CultureInfo.InvariantCulture.NumberFormat.

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