In.Net 4: PInvokeStackImbalance exception

I used the function strlenfrom msvcrt.dllin .Net 3.5 project. More specific:

private unsafe static extern int strlen( byte *pByte );

After migrating to .NET 4.0, if I use this function, it throws an exception PInvokeStackImbalance.

How to import .NET 3.5 msvcrt.dllor fix this exception?

+3
source share
4 answers

I suspect the problem is with the calling convention, you should use Cdecl.

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
private unsafe static extern int strlen(byte* pByte);
+10
source

, , - . , # (, , ):

  static int mystrlen( byte[] pbyte )
     {
     int i = 0;
     while ( pbyte[i] != 0 )
        i++;
     return i;
     }
+1

.NET 3.5 4. (, btw, msvcrt.dll - Runtime Microsft ++). , .

, "4", :

class Test
{
    public unsafe static void Main(string[] args)
    {
        byte[] bytes = new byte[] {70, 40, 30, 51, 0};
        fixed(byte* ptr = bytes)
        {
            int len = strlen(ptr);
            Console.WriteLine(len);
        }
    }
    [DllImport("msvcrt.dll")]
    private unsafe static extern int strlen(byte* pByte);       
}

, - strlen , , , . , , :

private static int managed_strlen(byte[] bytes)
{
    return bytes.TakeWhile(b => b != 0).Count();
}

Of course, this does not apply to multibyte (unicode) characters, but I don't think strlen is either.

+1
source

Just for fun:

public static unsafe int strlen(void* buffer)
{
    byte* end = (byte*)buffer;
    while (*end++ != 0);
    return(int)end - (int)buffer - 1;
}
+1
source

Source: https://habr.com/ru/post/1743018/


All Articles