声明特定长度的字符串
Declaring a string of a specific length
我需要从 Visual Basic 调用动态 link 库 (DLL) 中的一个函数,该库是用 C 实现的。C 函数具有签名
uint32_t F(char **str);
其中 str 是输出参数。数组 *str
预计至少有 n 个字符长。在 Visual Basic 方面,该函数声明为
<DllImport("lib.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function F(ByRef str As String) As UInteger
End Function
如何在 Visual Basic 中声明长度为 n 的字符串,使其与 C 函数 F 的形式参数兼容?
编辑:如果我像实例那样声明实际参数,函数调用将按预期工作
Dim str As String = " "
假设n是10。但是,n是一个变量。
VB中的String
实际上是C端的一个BSTR
,是WindowsAPI.[=16中的一个struct =]
在 C 端,您使用 Windows 函数,如 SysAllocString
来制造一个 BSTR,并使用 SysReleaseString
.
释放内存
您将无法(轻松地)在 C 和 VB 之间与 uint32_t F(char **str);
互操作。
您可以用 n 个空格填充一个字符串。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = ""
Dim n As Integer = 10
Dim paddedStr = s.PadRight(n)
Debug.Print(paddedStr.Length.ToString) 'Prints 10
End Sub
正如 TnTinMn 在其中一条评论中提到的,声明实际参数如下:
Dim str As New String(ChrW(0), n)
我需要从 Visual Basic 调用动态 link 库 (DLL) 中的一个函数,该库是用 C 实现的。C 函数具有签名
uint32_t F(char **str);
其中 str 是输出参数。数组 *str
预计至少有 n 个字符长。在 Visual Basic 方面,该函数声明为
<DllImport("lib.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function F(ByRef str As String) As UInteger
End Function
如何在 Visual Basic 中声明长度为 n 的字符串,使其与 C 函数 F 的形式参数兼容?
编辑:如果我像实例那样声明实际参数,函数调用将按预期工作
Dim str As String = " "
假设n是10。但是,n是一个变量。
VB中的String
实际上是C端的一个BSTR
,是WindowsAPI.[=16中的一个struct =]
在 C 端,您使用 Windows 函数,如 SysAllocString
来制造一个 BSTR,并使用 SysReleaseString
.
您将无法(轻松地)在 C 和 VB 之间与 uint32_t F(char **str);
互操作。
您可以用 n 个空格填充一个字符串。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = ""
Dim n As Integer = 10
Dim paddedStr = s.PadRight(n)
Debug.Print(paddedStr.Length.ToString) 'Prints 10
End Sub
正如 TnTinMn 在其中一条评论中提到的,声明实际参数如下:
Dim str As New String(ChrW(0), n)