Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

How to get a string from its pointer and length


  • Please log in to reply
4 replies to this topic
TheGood
  • Members
  • 589 posts
  • Last active: Mar 22 2014 03:22 PM
  • Joined: 30 Jul 2007
As the title says, I need the most efficient (read, fastest) way to retrieve a string if you only know its address and its length.
This is what I have right now:

sTest := "This is a test sentence."

MsgBox % PtrToStr(&sTest, StrLen(sTest))	;%

ExitApp

PtrToStr(ptr, len) {
	VarSetCapacity(s, len, 0)
	Loop %len%
		s .= Chr(*(ptr + A_Index - 1))
	Return s
}
Is there a faster way to do this?

Edit: I forgot to add, I tried messing around with RtlCopyString and RtlCopyBytes, but I get an ErrorLevel of -4 (function not found)

Lexikos
  • Administrators
  • 9844 posts
  • AutoHotkey Foundation
  • Last active:
  • Joined: 17 Oct 2006
If the string is always null-terminated (as with all AutoHotkey strings), the easiest way is:
sTest := "This is a test sentence."
MsgBox % DllCall("MulDiv", int, &sTest, int, 1, int, 1, str)
MulDiv(x,1,1) returns x unmodified, but DllCall interprets the return value as a string.

If the string isn't null-terminated or you want only a portion of the string, you may use lstrcpyn via DllCall.

TheGood
  • Members
  • 589 posts
  • Last active: Mar 22 2014 03:22 PM
  • Joined: 30 Jul 2007

MulDiv(x,1,1) returns x unmodified, but DllCall interprets the return value as a string.

Very interesting behaviour. Is that an AHK thing, or the dll itself? Is it because AHK knows it's a string pointer that was passed and not any number?

TheGood
  • Members
  • 589 posts
  • Last active: Mar 22 2014 03:22 PM
  • Joined: 30 Jul 2007
Sorry, didn't see the "str" in the return type parameter

SKAN
  • Administrators
  • 9115 posts
  • Last active:
  • Joined: 26 Dec 2005

sTest := "This is a test sentence."
MsgBox % DllCall("MulDiv", int, &sTest, int, 1, int, 1, str)
MulDiv(x,1,1) returns x unmodified, but DllCall interprets the return value as a string.


:shock: :D Thanks!
kWo4Lk1.png