0

I have a problem with my code, which it can be run on vb6 but somehow it crashed on vb.net

Public Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

And here is how i call that function:

Dim lRetval As Long
'Get Host IP Address in host.ini
sHostIP = Space(128)
lRetval = GetPrivateProfileString("HOSTPATH", "HOSTIP", "", sHostIP, Len(sHostIP), "Host.ini")

The error says:

Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'BDS ByPass!CreateBulkCIF.GlobalClass::GetPrivateProfileString' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'

Please help... I cant find any something useful anywhere.

chigarow
  • 53
  • 7
  • Try adding `CallingConvention = CallingConvention.Cdecl` in the import statement that you are missing... so something like ``. Just make sure to import `System.Runtime.InteropServices` in the class. Also the signature is wrong, I would verify it... – Trevor Oct 31 '18 at 01:55
  • *"I cant find any something useful anywhere"*. Really? I just did a web search for *"pinvokestackimbalance vb.net"* and the very first result was [this SO thread](https://stackoverflow.com/questions/10880198/pinvokestackimbalance-was-detected-visual-basic-2010) that has an answer that, while not accepted, does address your issue. Did you search for cat videos by mistake? – jmcilhinney Oct 31 '18 at 03:49

1 Answers1

2

The most common cause of this issue is using a function signature that was intended for VB6 rather than VB.NET. If you have a parameter or return of type Long then that is almost certainly the case. Windows API functions and other unmanaged APIs generally work with 32-bit integers. In VB6, the Long type was 32-bit and the Integer type was 16-bit. In VB.NET, the Long type is 64-bit and the Integer type is 32-bit. You should almost always be using Integer rather than Long in VB.NET.

Pinvoke.net shows the signature for that function as the following:

<DllImport("kernel32.dll", SetLastError:=True)>
Private Shared Function GetPrivateProfileString(ByVal lpAppName As String,
                                                ByVal lpKeyName As String,
                                                ByVal lpDefault As String,
                                                ByVal lpReturnedString As StringBuilder,
                                                ByVal nSize As Integer,
                                                ByVal lpFileName As String) As Integer
End Function

You should use that site as your first choice for VB.NET API signatures.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46