67
9.6.11 Using the API in Visual Basic .NET
6. Ensure that the DLL file is placed in the same folder as your application executable.
7. Import the functions you need from the DLL into your source code with the Declare
statement:
Private Declare Function CAN_Open Lib "CANDLL_STDCALL.dll" (ByVal
ComPort As String, ByVal szBitrate As String, ByVal acceptance_code
As String, ByVal acceptance_mask As String, ByRef Flags As IntPtr,
ByVal Mode As Integer) As Integer
8. Create a definition of the CAN_MSG structure for the CAN_Write and CAN_Read
functions, if needed.
Imports System.Runtime.InteropServices
Public Structure CAN_MSG
<MarshalAs(UnmanagedType.U4)>
Public Id As UInteger
<MarshalAs(UnmanagedType.U1)>
Public Size As Byte
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=8,
ArraySubType:=UnmanagedType.U1)>
Public Data As Byte()
<MarshalAs(UnmanagedType.U1)>
Public Flags As Byte
<MarshalAs(UnmanagedType.U2)>
Public Timestamp As UShort
End Structure
The keyword MarshalAs is used for all structure members to ensure that the
structure size corresponds to what the DLL expects.
To use the CAN_MSG structure, you will need to create an instance of the structure
you just defined.
Private myCANMSG As CAN_MSG
Before accessing this instance you just created for the first time, set the size for
the Data member to avoid “array out of bounds” error. This can be done in your
program’s constructor.
ReDim myCANMSG(7)