How pass an decimal from c# to vb6 with Interop

别来无恙 提交于 2019-12-20 02:27:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32266461/how-pass-an-decimal-from-c-sharp-to-vb6-with-interop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!