I'm attempting to use PInvoke to call an unmanaged C++ DLL and I'm getting errors (see below). Using
class __declspec(dllexport) MyClass
uint32_t runCommand(uint32_t start);
uint32_t MyClass::runCommand(uint32_t start);
uint32_t status = 1;
EntryPoint = "?runCommand@MyClass@myClass@@QAEII@Z",
CallingConvention = CallingConvention.Cdecl)]
public static extern UInt32 runCommand(UInt32 baseAddress);
public static void Do()
UInt32 a = 0xA000;
UInt32 ptr = runCommand(a);
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users...\TestApp.vshost.exe'.
Additional information: A call to PInvoke function 'TestApp!TestApp.CSMyClass::runCommand' 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.
There is a mismatch in calling conventions, which causes the stack unbalance.
runCommand is a member function of
MyClass, the calling convention used for it is not
__thiscall (note that there is an implicit "
this" pointer passed as argument with non-static member functions of C++ classes).
You may want to either export a pure C interface function (not a C++ class member function) from your DLL for P/Invoke'ing, or you can use C++/CLI to build a tiny bridging layer between native and managed code, wrapping your C++ native class in a .NET managed class written in C++/CLI, and use that managed class wrapper from C#.