gpt4 book ai didi

vb6 - 为什么 VarPtr(ByVal str) 的结果与 StrPtr(str) 相同? (VB6)

转载 作者:行者123 更新时间:2023-12-05 00:05:19 24 4
gpt4 key购买 nike

在VB6中VarPtr应该返回变量的地址,在本例中是变量的地址 str它在堆栈上分配,并在内存中保存一个指向字符串的指针。 StrPtr (或 StrPtr )应该返回内存中分配的字符串的地址。 ByVal应该只创建一个副本,但在这种情况下,它的工作方式很奇怪:

Dim str As String
str = "asd"
Debug.Print VarPtr(str)
Debug.Print VarPtr(ByVal str)
Debug.Print StrPtr(str)

结果是:
1636452 
110882980
110882980

为什么是 VarPtr(ByVal str)的结果同 StrPtr(str) ?

最佳答案

传递的字符串 ByVal在 BStr 中传递包含 C 字符串的第一个字符的地址。 StrPtr做同样的事情。

这样做的原因有两个。将 Unicode 传递给 API 调用和字符串构建。

将 Unicode 传递给 API 调用

您可以使用 StrPtr将 Unicode 字符串发送到 API 函数时,使用字符串而不是字节数组。

Dim ByteArr() as Byte
Var1="My Text"
ByteArr = Var1
APICall(ByteArr(0))
APICall(StrPtr(Var1))

两者都应该将 Unicode 字符串传递给 API 函数。使用 declare 时,Unicode 字符串被转换为 ANSI 字符串。声明为 Win 95 没有做 unicode。

弦楼

另一方面,如果您正在构建字符串,则使用 Left 将其内置到 VBA 中。 , Right , 和 Mid 声明 ,不是 功能 (他们重载)。
Sub Main()
Dim Var As String
Var = "gggggggggggg"
MsgBox StrPtr(Var)
Mid(Var, 1, 2) = "xx"
MsgBox StrPtr(Var) & " - " & Var
End Sub

ByVal Versus ByRef

Some authors like to say that the ByVal keyword is overloaded for strings, meaning that it takes on a different meaning when applied to strings than when applied to other variables. Frankly, I don't see it. Writing:

ByVal str As String 

tells VB to pass the contents of the BSTR (actually the ABSTR), which is the pointer to the character array. Thus, ByVal is acting normally--it just happens that the content of the BSTR is a pointer to another object, so this simulates a pass by reference. Similarly:

ByRef str As String

passes the address of the BSTR, as expected.



Win32 API Programming with Visual Basic,Chapter 6 Strings,O'Reilly,来自 MSDN Library 2001 年 10 月

StrPtr

Strings in Visual Basic are stored as BSTR's. If you use the VarPtr on a variable of type String, you will get the address of the BSTR, which is a pointer to a pointer of the string. To get the address of the string buffer itself, you need to use the StrPtr function. This function returns the address of the first character of the string. Take into account that Strings are stored as UNICODE in Visual Basic.

To get the address of the first character of a String, pass the String variable to the StrPtr function.

Example:

Dim lngCharAddress as Long
Dim strMyVariable as String
strMyVariable = "Some String"
lngCharAddress = StrPtr(strMyVariable)

You can use this function when you need to pass a pointer to a UNIOCODE string to an API call.



HOWTO:获取 Visual Basic Q199824 Microsoft 知识库中的变量地址,MSDN 2001 年 10 月。
VarPtr不是 VBA/VB6 语言的一部分,因此实现 VBA(如 Corel)的公司可能不会在他们的 VBA 中实现它。 VBA 规范在这里 https://msdn.microsoft.com/en-us/library/dd361851.aspx

关于vb6 - 为什么 VarPtr(ByVal str) 的结果与 StrPtr(str) 相同? (VB6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47499525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com