0

Hey all I am trying to convert a little bit of VB6 to .NET and I am getting the error of:

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Additional information: Conversion from string " " to type 'Integer' is not valid.

The following .net code is where its getting stuck at CopyMemory(str_Renamed, ptr, count):

Public Function ptrToStr(ByVal ptr As Integer) As String
Dim count As Integer
Dim str_Renamed As String

    count = lstrlen(ptr)

    If count Then
        str_Renamed = New String(vbNullChar, count)
        CopyMemory(str_Renamed, ptr, count)
        ptrToStr = str_Renamed
    Else
        ptrToStr = ""
    End If
End Function

The values for those varibles are:

count       = 4
ptr         = 268978536
str_Renamed = " "

I'm not sure how to go about fixing this error...

StealthRT
  • 10,108
  • 40
  • 183
  • 342
  • Stuff like this is usually best left to the marshaller, E.g. Marshal.PtrToStringAnsi/Auto() – Alex K. Jul 15 '17 at 13:21
  • This might be an example where code conversion is not a good practice. Chances are if you find out what the original code is trying to accomplish overall, there will be a better & easier .NET way to do the equivalent without any pointer / CopyMemory stuff. – StayOnTarget Jul 17 '17 at 11:15

1 Answers1

0

The problem looks to be that you are passing a string as the first parameter of the CopyMemory function. The CopyMemory function expects a pointer as the first parameter so the code is attempting to convert the string parameter to an integer. As far as I am aware, the only valid values for pointers are either integer values or hex values.

Mike_OBrien
  • 1,395
  • 15
  • 34