advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Rate this item | 0 users have rated this item.
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

VB.NET, however, doesn’t allow you to specify that marshaling attribute on parameters, so you must use the first declaration. Use a StringBuilder object as an alternative to using the VBByRefStr attribute.
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.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs