|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Structure may require marshalling attributes to be passed as an argument in this Declare statement
In Visual Basic 6.0, user-defined types could be passed as an argument in a Declare statement for a Windows API.
In Visual Basic .NET, a structure (user-defined type) passed as an argument in a Declare statement may require additional marshalling attributes in order to be passed correctly to the external function or subroutine. In particular, arrays and fixed-length strings may not function as expected without these attributes.
The following example shows a structure before and after upgrade:
' Visual Basic 6.0 code Type MyType s As String * 100 End Type ' After upgrade to Visual Basic .NET Structure MyType <VBFixedString(100), System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=100)> Public s As String End Structure
What to do next
- Add an Imports statement to reference the InteropServices namespace:
- Modify the structure and the string declaration to include marshalling attributes, as in the following example:
' Modified code <StructLayout( LayoutKind.Sequential, CharSet:=CharSet.ANSI)>Structure MyType <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=100)> Public s As String End Structure