使用VB.net程序,通过Socket按字节发送结构与Delphi程序通讯,经调试可以运行的给100分,其他有帮助的也有分,分不够我将在揭帖时追加,Delphi数据接口结构如下:
Type SendDataType =Record
aa:String[20];
bb :TDateTime;
cc :array[0..60] of single;
dd:string[60];
end;
欢迎讨论。
...全文
7013打赏收藏
高分求教:用structure结构自定义数据接口与Delphi接口通讯问题。分不够再加
使用VB.net程序,通过Socket按字节发送结构与Delphi程序通讯,经调试可以运行的给100分,其他有帮助的也有分,分不够我将在揭帖时追加,Delphi数据接口结构如下: Type SendDataType =Record aa:String[20]; bb :TDateTime; cc :array[0..60] of single; dd:string[60]; end; 欢迎讨论。
<StructLayoutAttribute(LayoutKind.Sequential, CharSet:=CharSet.Ansi, pack:=1)> _
Public Structure SendDataType '接口数据结构
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=20)> Dim aa As String
Dim bb As Double 'Delphi的日期在VB里是Double
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=60)> Dim cc() As Single
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=60)> Dim cc As String
End Structure
'***********************************************
' **************************构体与字节数组转换*****************
Private Function StructureToByteArray(ByVal tag As SendDataType) As Byte()
Dim iSize As Integer = Marshal.SizeOf(tag)
Dim ptr As IntPtr = Marshal.AllocHGlobal(iSize)
Marshal.StructureToPtr(tag, ptr, True)
Dim ba(iSize - 1) As Byte
Marshal.Copy(ptr, ba, 0, ba.Length)
Marshal.FreeHGlobal(ptr)
Return ba
End Function
Private Sub ByteArrayToStructure(ByVal ba() As Byte, ByRef tag As SendDataType)
Dim ptr As IntPtr = Marshal.UnsafeAddrOfPinnedArrayElement(ba, 0)
tag = Marshal.PtrToStructure(ptr, tag.GetType)
End Sub
Class StateObject
' Client socket.
Public workSocket As Socket = Nothing
' Size of receive buffer.
Public BufferSize As Integer = 512
' Receive buffer.
Public buffer(512) As Byte
' Received data string.
Public sb As New StringBuilder
End Class 'StateObject
好象有点不对吧?
21无论如何都是不对的啦,应该是19吧?
Delphi的String对应VB的Char吗?忘了,好像也不是吧?(呵呵,真的忘了)
那个TDateTime很可能是一个Float64的OleDateTime的东东,如果你看Delphi文档说TDateTime是用某种浮点格式保存的,或者由某种转换到(转换自)浮点类型数据的方法,那么很可能就是我说的那个意思了。这样的话可以是一下定义为double,然后通过DateTime.FromOADate这个函数转换成DateTime。
array[0..60] of single 就是 As Single[60]