(Type your message here)
--------------------------------
From: Tien Pham
I am having problems with intptr. Or maybe i am not using it properly. What it is that i am having problem with is the marshaling a structure to an ptr. For instance, i have a structure declared as followed:
<StructLayout(LayoutKind.Sequential, Pack:=1)> Public Structure AG_Mem_Msg
Public dle As Byte
Public stx As Byte
Public addr As Short
Public status As Byte
Public command As Byte
Public subcode As Byte
Public param_cnt As Byte
Public byte_cnt_1 As Byte
Public mem_type As Byte
Public page_num As Byte
Public ofs_addr As Short
Public byte_cnt_2 As Byte
Public data_ptr As IntPtr
End Structure
The dataptr in this structure is the buffer that i will store my data for tranmitting out the comm port. It varies from 2 byte to a max of 243 bytes. I can assign all of the other values simply by
AG_Mem_Struct.dle = &H10
AG_Mem_Struct.stx = &H2
AG_Mem_Struct.addr = ((COMM.DRIVER_CFG.RTU_ADDR << 8) + (COMM.DRIVER_CFG.RTU_ADDR >> 8))
AG_Mem_Struct.status = 0
AG_Mem_Struct.command = &HB
AG_Mem_Struct.subcode = &H1
AG_Mem_Struct.param_cnt = &H1
AG_Mem_Struct.byte_cnt_1 = &H5
AG_Mem_Struct.mem_type = CByte(Me.cbx_MemType.SelectedIndex)
AG_Mem_Struct.page_num = CByte(Me.cbx_PageNum.SelectedIndex)
AG_Mem_Struct.ofs_addr = uiHex
AG_Mem_Struct.byte_cnt_2 = System.Convert.ToByte(Me.txt_AddCnt.Text, 16)
The question to this post is how can i store from 1....n number of bytes my data_ptr and copy it to the byte array?
I tried doing this but is failed on me.
I did not know how to index into a intptr so i had to put my data in an array the copy it to my pointer...
Dim array(1) As Byte
array(0) = &H10
Marshal.Copy(array, 0, AG_Mem_Struct.data_ptr, 2)
TMP_Q_DEF.TX_COUNT = 18 ' this is including the crc values
TMP_Q_DEF.RX_COUNT = &HFF
' i tried to copy the data to a temp array and then copy it to my buffer...
Dim TempPtr As IntPtr = Marshal.AllocHGlobal(TMP_Q_DEF.TX_COUNT)
Marshal.StructureToPtr(AG_Mem_Struct, TempPtr, True)
Marshal.Copy(TempPtr, TMP_Q_DEF.TX_PTR, 0, TMP_Q_DEF.TX_COUNT)
Marshal.FreeHGlobal(TempPtr)
' i got an error. Also, don't you need to allocate memory for the dataptr?
Thank you!
Tien
-----------------------
Posted by a user from .NET 247 (http://www.dotnet247.com/)
<Id>tpm7co272kOXe2ekQP66vA==</Id>