Previous | Index | Next 

[PRB] Structures containing DBCS strings may cause exceptions when passed to an external (Declare) method

VB Migration Partner automatically decorates structure members with attributes, to facilitate passing the structure to external methods. This is typically the case for String, Boolean and array items, among the others. In most cases, VB Migration Partner’s guess is correct and you don’t need to do anything else; in other cases, however, you might need to manually modify those attributes.

More specifically, consider this VB6 code:

        Type TestUDT
            StringField As String * 30
        End Type

Assuming that a UseSystemString pragma is in effect, the code is translated to VB.NET as follows:

        Structure TestUDT
            <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=30)> _
            Private m_StringField As String
            ...
        End Structure

Interestingly, applying the Len6() method to this structure returns the correct value (that is, 30), which indirectly confirms that the translation is correct. However, one Japanese customer reported that passing this structure to an external method throws a COMException error, with the following message:

 "The data area is too small to be passed to a system call. (Exception from HRESULT: 0x8007007A)"

(This error doesn’t occur on systems that use standard, Unicode strings). The fix for this problem is changing the argument of the MarshalAs attribute, as follows:

        <MarshalAs(UnmanagedType.LPStr, SizeConst:=30)>  _
        Private m_StringField As String

While this fix makes the call work correctly, it causes the Len6 method return an incorrect value, therefore you cannot count on the Len6 method any longer. Unfortunately, this is one of those differences between VB6 and VB.NET cannot be solved by an automatic conversion tool.

We have also found that another way to avoid the exception is marking the structure with CharSet=Auto, as follows:

        <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
        Structure TestUDT
            ...
        End Structure

 

Previous | Index | Next