 |
|
 |
module abc
Public Declare Function Command Lib "InnTechSSP.dll" (ByRef Src As UDT) As UDT
Structure UDT
Public rxstatus As Short
Public datalen As Byte
Public array1() As Byte
Public Sub Initialize()
ReDim array1(254)
End Sub
End Structure
Public Const REJECT_NOTE_CMD As Integer = &H8
Public Const BULB_ON_CMD As Integer = &H3
Public Const BULB_OFF_CMD As Integer = &H4
Public Const DISABLE_CMD As Integer = &H9
Public Const DISPENSE_CMD As Integer = &H12
Public Const ENABLE_CMD As Integer = &HA
Public Const POLL_CMD As Integer = &H7
Public Const RESET_CMD As Integer = &H1
Public Const PROGRAM_CURRENCY_CMD As Integer = &HB
Public Const SETUP_REQUEST_CMD As Integer = &H5
Public Const SET_INHIBITS_CMD As Integer = &H2
Public Const HOST_PROTOCOL As Integer = &H6
Public Const SERIAL_NUMBER As Integer = &HC
Public Const SET_INHIBITS As Integer = &H2
Public Const SYNC_CMD As Integer = &H11
Public Const FILE_HEADER As Integer = &H12
Public Const PROG_STATUS As Integer = &H16
Public Const UNIT_DATA As Integer = &HD
Public Const VALUE_DATA As Integer = &HE
Public Const SECURITY_DATA As Integer = &HF
Public Const CHANNEL_RETEACH As Integer = &H10
Public Const OK As Integer = &HF0
Public Const SLAVE_RESET As Integer = &HF1
Public Const COMMAND_NOT_KNOWN As Integer = &HF2
Public Const WRONG_No_PARAMETERS As Integer = &HF3
Public Const PARAMETER_OUT_RANGE As Integer = &HF4
Public Const COMMAND_NOT_PROCESS As Integer = &HF5
Public Const SOFTWARE_ERROR As Integer = &HF6
Public Const DISABLED As Integer = &HE8
Public Const NOTE_READ As Integer = &HEF
Public Const DISPENSING As Integer = &HE1 '
Public Const REJECTING_MS As Integer = &HED
Public Const DISPENSED As Integer = &HE2
Public Const REJECTED_MS As Integer = &HEC
Public Const FRAUD_ATTEMPT_MS As Integer = &HE6
Public Const NOTE_STACKED As Integer = &HEB
Public Const STACKING As Integer = &HCC
Public Const CREDIT As Integer = &HEE
Public Const SAFE_JAM As Integer = &HEA
Public Const UNSAFE_JAM As Integer = &HE9
Public Const STACKER_FULL As Integer = &HE7
end module
Friend Class Form1
Inherits System.Windows.Forms.Form
Dim Src As New UDT
Dim Cpy As New UDT
Private Sub CmdStart_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles CmdStart.Click
IntNReaderPort = 3
If fn_StartReader() = True Then
Timer1.Enabled = True
Else
Timer1.Enabled = False
MsgBox("Error in Fnction Start")
End If
End Sub
Private Function fn_StartReader() As Boolean
fn_StartReader = False
try
If OpenPort(IntNReaderPort) = 1 Then
System.Windows.Forms.Application.DoEvents()
Src.datalen = 1
Src.array1(0) = SYNC_CMD
'UPGRADE_WARNING: Couldn't resolve default property of object Cpy. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
Cpy = Command(Src)
a = Command(Src, Cpy)
Src.datalen = 1
Src.array1(0) = SETUP_REQUEST_CMD
'UPGRADE_WARNING: Couldn't resolve default property of object Cpy. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
Cpy = Command(Src)
If Cpy.rxstatus = 0 Then
Call CloseComm()
BlnReaderHanged = True
MsgBox("Note Reader Hanged")
'Try to restart
ElseIf Cpy.rxstatus = 2 Then
Call CloseComm()
BlnReaderHanged = True
MsgBox("Note Reader Not Found...")
ElseIf Cpy.rxstatus = 1 Then
Src.datalen = 3
Src.array1(0) = SET_INHIBITS
Src.array1(1) = &HFF
Src.array1(2) = &HFF
'UPGRADE_WARNING: Couldn't resolve default property of object Cpy. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
Cpy = Command(Src)
Src.datalen = 1
Src.array1(0) = ENABLE_CMD
'UPGRADE_WARNING: Couldn't resolve default property of object Cpy. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
Cpy = Command(Src)
fn_StartReader = True
Exit Function
Else
MsgBox("Note Reader Not Found")
End If
Else
MsgBox("Port Error")
End If
Exit Function
catch ex as exception
MsgBox("Error in Process...")
End try
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Src.Initialize()
Cpy.Initialize()
End Sub
End Class
|
|
|
|
 |
|
 |
Hi i have a problem with the VB 6 applications.When i am running my application ie for example i am continously amending the data through the VB screen after a some time the screen is crashing..i am unable to view the screen..it is becoming blank and getting the message out of memory.Is there any solution for this?Please help.
|
|
|
|
 |
|
 |
Hi, i'm developing an application that calls some C library from C#, but i have some problem with memory occupation. I cannot understand the difference between DestroyStructure() and FreeCoTaskMem() methods. The result is that the memory occupation of my application grow up until an out of memory exception appears.
I have defined classes like the following
public class myClassA
{
public IntPtr stringID = IntPtr.Zero;
public float thickMeas;
public float speedMeas;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 7]
public Single[] tempMeas = new Single[7];
}
public class myClassB
{
public IntPtr ptrClassA = IntPtr.Zero;
public IntPtr ptrClassC = IntPtr.Zero;
......
}
I create an object of myClassA and myClassB then , i associate the ptrClassA to the address of object of myClassA (using appropriate static method of Marshal class) then the myClassB object is referenced by an IntPtr variabile which is used as input for the C library.
What memory releaser should I invoke? FreeCoTaskMem(), DestroyStructure() or both?
Thanks in advance
sampdoria
|
|
|
|
 |
|
 |
Your example on Structure to Byte Array and Byte Array to Structure suits my current project which requires to sent and receive data from an external device. I need to use every byte in the structure to calculate a checksum for verification purposes. However, I could not seems to get it working when the structure contains a string data type. It seems that the structure contains a 4 byte field containing a pointer to the string. Would appreciate if you could provide an example such as shown below. Public Structure structTest Public devName As String '10 bytes long Public Weight As Long Public percent As Double End Structure The size of the byte array to store the structure should be 26 but my testing using your code example indicates 20. The problems lies with how to get the 10 char devname into a byte array of size 10. The code I use are listed below Dim Tst As structTest Dim ByteArray() As Byte Tst.UserId = "1234567890" Tst.Weight = 23 Tst.percent = 50.1 Dim Ptr As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(Tst)) ReDim ByteArray(Marshal.SizeOf(Tst) - 1) 'now copy strcutre to Ptr pointer Marshal.StructureToPtr(Tst, Ptr, False) Marshal.Copy(Ptr, ByteArray, 0, Marshal.SizeOf(Tst)) 'now use ByteArray ready for use Marshal.FreeHGlobal(Ptr)
|
|
|
|
 |
|
 |
You should decorate your structure as follows: <StructLayout(LayoutKind.Explicit, Pack:=1)> _ Public Structure structTest <FieldOffset(0)> Public devName As String '10 bytes long <FieldOffset(10)> Public Weight As Long <FieldOffset(14)> Public percent As Double <FieldOffset(22)> Public checksum AS Short End Structure to get the size of the structure and the field positions exactly where you want them. You may also be able to use <StructLayout(LayoutKind.Sequential, Pack:=1)> - I have not checked.
|
|
|
|
 |
|
 |
I tried your code, and found out PtrToStructure no work on .net 2.0 cf
I tried read byte array from a file on device, using FileStream.Read
then try to copy it into a structure, but at runtime, I got NotSupportedException.
do you have any idea?
charles
|
|
|
|
 |
|
 |
Hi. I have the same problem too at the moment. Reading a ByteArray from HDD. I have my own Structure
_
Private Structure RGBQUAD
Public rgbBlue As Byte
Public rgbGreen As Byte
Public rgbRed As Byte
Public rgbReserved As Byte
End Structure
Private ColorTable() As RGBQUAD
Redim ColorTabel(256)
Dim A() As Byte
'--> I Read data from File to A
'Now all data is in the Bytearray A(1024)
'But how the get it into the ColorTable?
I have CF.Net too.
Regards
Timo
|
|
|
|
 |
|
 |
Hi, your articles are great, but Ijust dont understand what is going on with my api call.
Here is the story. I am useing the MTPLib.dll from the Media Transport Protocol kit from Microsoft. I have a whole application developed that is currently working. Now, one API call I use is this:
Sub GetObjectHandles(ByVal StorageId As UInteger, ByVal FormatCode As MtpLib.MTP_FORMATCODE, ByVal ParentObjectHandle As UInteger, ByRef pcelt As Integer, ByVal ppObjectHandles As System.IntPtr, ByRef pResponseCode As MtpLib.MTP_RESPONSECODE)
I use :
MTP.GetObjectHandles(65537, 0, 0, pCelt, objHandles, resCode)
All variables are declared properly. BUT this throwsan access violation every time I call it. I know the API call works because the pCelt reaches 312 (the same number of file as my device). I know that this has to be marshalled but how? I know that the IntPtr holds an array of file handles and I know pCelt hold the total count of the handles returned, but how do i get the object handles and how to pull them out of the array one at a time to use then say for example in a list box. I absolutely know that it needs to be marshaled, because I can get file handles back , but they are not returnedproperly becuase it produces random numbers.
Please help....this is driving me nuts!
|
|
|
|
 |
|
 |
First let me say thank you for writing a very nice article on Marshaling structures into byte arrays it is very helpful. However I am having a problem with the part of the article that references complex structures. It doesn’t work. I have gone so far as to copy and past the code you have into VB.NET and compiled and run it. While it executes fine the data that is stored in the StrtoBy array is not the data that is in the structure. I actually appears to be related to the memory location of the pointer. I was thinking that it was because in this section of code you do not use Marshal.StructureToPtr function.
I attempted to add this myself think that this would solve my problem. However instead of copying the Structure to the pointer it throws an exception error. See below. An unhandled exception of type 'System.NullReferenceException' occurred in <Project Name> Additional information: Object reference not set to an instance of an object. This only seems to occur if you have any array of structures, such as you use in your example. I am looking forward to hearing from you on this issue. Does anyone know how to solve this problem? Thanks Justin
|
|
|
|
 |
|
 |
Private Function BulidStr(ByVal Buff() As Byte, _
ByVal MyType As System.Type) As Object
Dim MyGC As GCHandle = GCHandle.Alloc(Buff, GCHandleType.Pinned)
‘Marshals data from an unmanaged block of memory
'to a newly allocated managed object of the specified type.
Dim Obj As Object = _
Marshal.PtrToStructure(MyGC.AddrOfPinnedObject, MyType)
Return Obj ' << Will skip the rest of the app
‘Free GChandle to avoid memory leaks
MyGC.Free() ' << Never executes
End Function
tridy
Klaipeda, Lithuania
|
|
|
|
 |
|
 |
... exactly
Put the line "Return Obj ' << Will skip the rest of the app"
right before "End Function" and it works fine
Claus
|
|
|
|
 |
|
 |
Structure Test
Public ABC As String
Public MyNumber As Integer
End Structure
I am trying like the following...
Dim TESTB As Test ' Stuctuer variable
Dim ByteArray1() As Byte
Dim bytesRec As Integer = handler.Receive(bytes)
ByteArray1 = System.Text.ASCIIEncoding.ASCII.GetBytes(bytesRec)
'copy byte array data to structure
TestB = BulidStr(ByteArray1, TestB.GetType)
'Now use it and display it
MessageBox.Show(TEStB.ABC.ToString)
'''''
Public Shared Function BulidStr(ByVal Buff() As Byte, ByVal MyType As System.Type) As Object
Dim MyGC As GCHandle = GCHandle.Alloc(Buff, GCHandleType.Pinned)
'Marshals data from an unmanaged block of memory
'to a newly allocated managed object of the specified type.
Dim Obj As Object = Marshal.PtrToStructure(MyGC.AddrOfPinnedObject, MyType)
Return Obj
'Free GChandle to avoid memory leaks
MyGC.Free()
End Function
'''''
I am getting,
System.NullReferenceException - Object reference n ot set to an instance of an object.
When I tried converting this to structure
-- modified at 6:42 Thursday 8th June, 2006
|
|
|
|
 |
|
 |
How do you convert a byte array to a structure array? I was trying the following...
Structure Account
Dim Balance as Double
Dim Overdraft as Double
End Structure
Dim Accounts(8) As Account
Accounts= BuildStr(ByteArray, Accounts.GetType)
Would get exception about no parameterless constructor
Thanks,
Justin
|
|
|
|
 |
|
 |
This is the structure:
STRUCTURE A
HeaderType as string ' 2 characters
HeaderVersion As Short ' 100 means version 1.00
Serial As String ' 24 chars
Phone As String ' 12 chars
END STRUCTURE
My VB.NET app will send this structure to a Visual C DLL and this DLL will talk to a UNIX Server. As you know, the DLL and the program on the server side require fixed length of strings.
Suppose:
HeaderType = "10"
HeaderVersion = 100
Serial = "RS001002003004005" ' add spaces so that it is 24 chars
Phone = "123-123-1234"
Marshal and get the pointer by using StructureToPtr (Marshal.StructureToPtr)
Immediately use PtrToStructure, and check the value, it is like this:
HeaderType ="1"
HeaderVersion = 100
Serial = "RS00100200300400" ' add spaces so that it is 24 chars
Phone = "123-123-123"
If check the Hex values, I find the last character of each string is replaced by '\0'.
My Visual C DLL function is like this:
Declare Function RsHostMessage Lib "RSRSCW32.DLL" Alias "RSHMSG" (ByRef Ctrl As RsHostCtrlDef, ByVal servclass As String, ByVal MsgOut As IntPtr, ByVal OutLen As Short, ByVal MsgIn As IntPtr, ByVal InLen As Short, ByRef RdCnt As Short) As Short
And the Visual C function decalration is:
short __declspec(dllexport) WINAPI RsHostMessage(RS_HOST_CTRL_DEF *Ctrl, char *ServClass, VOID *MsgOut, USHORT OutLen, VOID *MsgIn, USHORT InLen, USHORT *RdCnt)
How could I aviod this?
By the way, Tried to make the string longer and tried to use the structure instead of IntPtr. Not work.
Thanks!
|
|
|
|
 |
|
 |
As u r sending code from managed to unmanaged world. So better to declare your API function RsHostMessage with attribute to cover data marshling problems.
|
|
|
|
 |
|
 |
Thanks.
I solved this problem.
Decalre the function as follows:
Declare Function RsHostMessage Lib "RSRSCW32.DLL" Alias "RSHMSG" (ByRef Ctrl As RsHostCtrlDef, ByVal servclass As String, ByVal MsgOut As StringBuilder, ByVal OutLen As Short, ByVal MsgIn() As Byte, ByVal InLen As Short, ByRef RdCnt As Short) As Short
The only trouble is I have to convert all structures into byte array. BUT it does work fine. So no marshalling is needed.
|
|
|
|
 |