Reputation: 1
After i migrated from Framework 2 to framework 4, i get an error when i run the WriteFile function.
[DllImport("kernel32.dll")]
public static extern bool WriteFile(SafeHandle hFile,
byte[] lpBuffer,
uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten,
long lpOverlapped);
Solution:
[DllImport("kernel32.dll")]
public static extern bool WriteFile(SafeHandle hFile,
byte[] lpBuffer,
uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten,
**Int32** lpOverlapped);
The lpOverlapped parameter should be a int32, which is an unsigned long in umanaged C++.
Original Error:
PInvokeStackImbalance was detected Message: A call to PInvoke function '' 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.
Upvotes: 0
Views: 1732
Reputation: 612854
lpOverlapped
is a pointer and you should declare it as IntPtr
, or as a ref
parameter.
You are running a 32 bit process and were formerly passing a 64 bit integer, long
, when a pointer was expected. The newer version of the .net runtime detects the error.
The solution is most definitely not to declare the parameter as Int32
. That will then be wrong if you ever compile to a 64 bit target.
Since you appear not to be using overlapped I/O I would just use IntPtr
and pass IntPtr.Zero
.
[DllImport("kernel32.dll")]
static extern bool WriteFile(
IntPtr hFile,
byte[] lpBuffer,
uint nNumberOfBytesToWrite,
out uint lpNumberOfBytesWritten,
IntPtr lpOverlapped
);
Upvotes: 1