-1

I've been trying to figure out why the function below throws an error saying "Type Mismatch" when it returns. From what I know about VB6, this should work without any issue, yet it obviously does not. Can anyone see what I am doing wrong here and let me know how I can fix it? Thanks in advance.

Private Function GetByteArray(source As Variant, index As Integer, length As Integer) As     Variant
  Dim buff() As Byte
  ReDim buff(0 To length - 1)
  Dim i As Integer
  For i = 0 To length - 1
    buff(i) = CByte(source(index + i))
  Next i
  GetByteArray = buff
End Function
Ilya Kurnosov
  • 3,180
  • 3
  • 23
  • 37
Brandon
  • 890
  • 2
  • 13
  • 32
  • The Function is trying to return a variant, and you've dimmed buff as a byte. Seems like you want to return a byte from that function, otherwise why are you converting it? Unless I'm misunderstanding the question. – Joe M Apr 12 '13 at 18:33
  • This might help: http://support.microsoft.com/default.aspx?kbid=250344 – Joe M Apr 12 '13 at 18:39
  • right, what I really want to get is a byte array. If I wanted a single byte, that would be quite simple to do. I was basically following the example provided in http://support.microsoft.com/kb/317030. Of course my source is a Variant containing a byte array rather than a string. – Brandon Apr 12 '13 at 19:12
  • How do you call your function? Specifically, what do you pass as `source`? At what line do you get `Type Mismatch` error, exactly? – Ilya Kurnosov Apr 12 '13 at 20:07
  • Specifically, I am passing in a Variant containing a byte array that was returned from a 3rd party library. The Type Mismatch error was getting thrown as soon as the function returned. Which is why I assumed that there was something wrong with the function. However it looks like the real problem is what I'm doing with the result of the function. – Brandon Apr 12 '13 at 20:36

1 Answers1

1

It turns out that the problem did not have anything to do with the Function I posted, but rather with what I was doing with the result. I was using the method to get the bytes of a double, and then using CDbl to get the double value. This is where the error was really happening.

The way I should have been doing this is to use the following code:

CopyMemory rfcTest.rfcFloat, GetByteArray(buff, 0, 8), Len(rfcTest.rfcFloat)

Note that in order to use this, you must also declare the CopyMemoryMethod like this:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSrc As Any, ByVal ByteLen As Long)
Brandon
  • 890
  • 2
  • 13
  • 32