imazen/imageflow-dotnet

PInvokeStackImbalance exceptions on Net 4.8/x86 with possible resolution

jakenuts opened this issue · 3 comments

Using the latest build in a .NET 4.8 console app set to x86 produces the exception below whenever the native exports are called. As mentioned in issue #1 the code still works but it does trigger a bit of anxiety about moving to production. The behavior can be reproduced with the repo linked at the bottom.

PInvokeStackImbalance
'A call to PInvoke function 'Imageflow.Net!Imageflow.Bindings.NativeMethods::imageflow_context_create' 
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.'

One thing I discovered is that if you add the Cdecl calling convention to all the DllImports in NativeMethods the exceptions go away. I'm way beyond my depth in interop so I'm not sure of the unintended consequences of making the caller responsible for clearing the stack, but if that's already expected it would be a great update.

Thanks!

James White

[DllImport("imageflow", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool imageflow_abi_compatible(uint imageflowAbiVerMajor, uint imageflowAbiVerMinor);

[DllImport("imageflow", CallingConvention = CallingConvention.Cdecl)]
public static extern uint imageflow_abi_version_major();        

Environment:
Windows 10 Pro 20H2 x64 on x64 processor
Visual Studio Professional 2019 16.8.3
Imageflow.net 0.7.20
ImageFlow.NativeRuntime.win-x86 v1.5.5-rc59

Reproducing example
https://github.com/machew/ImageFlow-x86-Test

Thank you for reporting this! I will investigate. Did you notice if switching to Cdecl messed up running in 64-bit?

Also, in general we don't recommend using 32-bit mode due to ram limitations. If you're running a server it may not be sufficient to handle a high number of concurrent operations.

Try v0.7.21

That seems to work great, thanks for the speedy fix, @lilith !