advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Expertise: Intermediate
Language: .NET
July 3, 2002
Return Strings From an API

In .NET, strings are immutable: When you pass them out to an API, you can’t modify them. However, VB.NET applies the VBByRefStr unmanaged type-marshaling attribute to the string. This allows VB.NET to create a temporary buffer, copy that back to a new string, then point the original string to the new string:

Public Declare Function GetWindowText _
Lib "User32.Dll" _
(ByVal hwnd As Int32, _
ByVal lpString As String, _
ByVal cch As Int32) As Int32

To use this declaration, simply initialize the string to the right size:

Dim s As String = Space(256)
Dim rtn as Int32 = GetWindowText(hwnd, s, 256)

The API declaration is equivalent to:

Public Declare Function GetWindowText _
Lib "User32.Dll" (ByVal hwnd As Int32, _
<System.Runtime.InteropServices.MarshalAs( _
Runtime.InteropServices.UnmanagedType.VBByRefStr)> _
ByRef lpString As String, _
ByVal cch As Int32) As Int32

It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com.
Already a member?





Bill McCarthy
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
advertisement
advertisement