另一個方式就是採用 string 直接 copy 進 structure 的方式,網路上找到的是 c# 的 code.. 要直接轉到 vb.net 也有些地方需要更動…
有 c# 的需求的可以看原文: How to copy a String into a struct using C#
以下提供 VB.net 的程式碼:
Imports System.Text
Imports System.Runtime.InteropServices
Public Class Form1
Structure myStruct
Public a As String
Public b As String
Public c As String
End Structure
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim buffer As String = "abcdefgh2223333"
Dim pBuf As IntPtr = Marshal.StringToBSTR(buffer)
Dim ms As myStruct = CType(Marshal.PtrToStructure(pBuf, GetType(myStruct)), myStruct)
Console.WriteLine("fname is: {0}", ms.a)
Console.WriteLine("lname is: {0}", ms.b)
Console.WriteLine("phone is: {0}", ms.c)
Marshal.FreeBSTR(pBuf)
End Sub
End Class
沒有留言:
張貼留言
留言請留下大名~謝謝。