1

I am new to interfacing a C# .exe project to native Visual-C++ DLL.

I can't figure out how to pass just a simple integer, and the following code results in a popup error about "PInvoke ... unbalanced the stack".

C++ DLL...........

 extern "C"
 {

__declspec(dllexport) void start_frame_generation(  int& test_num )
{
    Console::WriteLine ("test_num = " + test_num );
    }

C# .......................

    [DllImport("Ultrasound_Frame_Grabber.dll")]
public static extern void start_frame_generation(  ref int test_num );

    private void VNGuideViewForm_Load(object sender, EventArgs e)
    {

            int test_num = 123;
            start_frame_generation( ref test_num);
     }
apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69
Doug Null
  • 7,989
  • 15
  • 69
  • 148
  • i think u need to tell c# that its a declspec function see http://stackoverflow.com/questions/5602645/why-do-i-get-pinvokestackimbalance-was-detected-for-this-simple-example – pm100 Jul 11 '13 at 17:33

2 Answers2

4

You need to add CallingConvention = CallingConvention.Cdecl to your DllImport like so:

[DllImport("Ultrasound_Frame_Grabber.dll", CallingConvention = CallingConvention.Cdecl)]

Omitting this declaration will cause the unbalanced stack message you are seeing.

Compilers before VS2010 assumed CallingConvention.Cdecl but since then you had to add it unless you are calling one of the Win32 APIs.

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
0

pm100 is correct. You need to tell the p/invoke marshaller that the function is using C declaration (as opposed to StdCall, which is default). Inside the DllImport attribute, add the following parameter: CallingConvention = CallingConvention.Cdecl

The various calling conventions determine both how the arguments to a function are placed on the stack as well as who is responsible for cleaning up the stack (the function caller or the function that is called). If you use the incorrect calling conventions, the stack will have a different size than expected after the function completes, which results in this error.

DevPrime
  • 901
  • 8
  • 5