Attribute VB_Name = "POS_CIDR"
Option Explicit

Private Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long

Private Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Private Declare Function lstrlenA Lib "kernel32" (ByVal lpString As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal lpDest As Long, ByVal lpSource As Long, ByVal nBytes As Long)

Private Declare Function CIDR_Info_int Lib "POS_CIDR.dll" Alias "CIDR_Info" () As Long
Private Declare Function CIDR_SaveLine_int Lib "POS_CIDR.dll" Alias "CIDR_SaveLine" (ByVal line As Long, ByVal filename As Long, ByVal param As Long) As Long
Private Declare Function CIDR_RegisterEvent Lib "POS_CIDR.dll" (ByVal funcPtr As Long, ByVal mask As Long) As Long
Public Declare Function CIDR_PlayLine Lib "POS_CIDR.dll" (ByVal line As Long) As Long

Private Function GetStringFromPointerW(ByVal lpString As Long) As String
  Dim lngLength As Long, strBuffer As String
  lngLength = lstrlenW(lpString) 'get length of string (in chars)
  strBuffer = Space$(lngLength) 'make a buffer to copy to
  CopyMemory StrPtr(strBuffer), lpString, lngLength * 2 'copy the string (note that this is a unicode string, so really there are 2 bytes per char
  GetStringFromPointerW = strBuffer 'return the copied string
End Function

Private Function GetStringFromPointerA(ByVal lpString As Long) As String
  Dim lngLength As Long, strBuffer As String
  lngLength = lstrlenA(lpString) 'get length of string (in chars)
  strBuffer = Space$(lngLength) 'make a buffer to copy to
  Dim i As Long
  For i = 1 To lngLength
    CopyMemory StrPtr(strBuffer) + 2 * (i - 1), lpString + i, 1 'copy the string (note that this is a unicode string, so really there are 2 bytes per char
  Next
  GetStringFromPointerA = strBuffer 'return the copied string
End Function

Public Function CIDR_Load() As Boolean
  Dim hand As Long
  hand = LoadLibrary("POS_CIDR.dll")
  If (hand <> 0) Then
    Dim r As Long
    r = CIDR_RegisterEvent(AddressOf CIDR_Callback_int, 5)
  End If
  CIDR_Load = (hand <> 0)
End Function


Public Function CIDR_Info() As String
  CIDR_Info = GetStringFromPointerW(CIDR_Info_int())
End Function


Public Function CIDR_SaveLine(line As Long, filename As String, param As String) As Long
  CIDR_SaveLine = CIDR_SaveLine_int(line, StrPtr(filename), StrPtr(param))
End Function


Private Sub CIDR_Callback_int(ByVal line As Long, ByVal msg As Long)
  Dim msgstr As String
  msgstr = GetStringFromPointerW(msg)
  FormDemo.CIDR_Event line, msgstr
End Sub

