1

我不熟悉将 C# .exe 项目连接到本机 Visual-C++ DLL。

我不知道如何只传递一个简单的整数,以下代码会导致弹出错误提示“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);
     }
4

2 回答 2

4

CallingConvention = CallingConvention.Cdecl您需要DllImport像这样添加:

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

省略此声明将导致您看到的不平衡堆栈消息。

VS2010 之前的编译器假定CallingConvention.Cdecl但从那时起您必须添加它,除非您正在调用 Win32 API 之一。

于 2013-07-11T17:59:38.440 回答
0

pm100 是正确的。您需要告诉 p/invoke 编组器该函数正在使用 C 声明(而不是默认的 StdCall)。在 DllImport 属性中,添加以下参数: CallingConvention = CallingConvention.Cdecl

各种调用约定决定了函数的参数如何放在堆栈上以及谁负责清理堆栈(函数调用者或被调用的函数)。如果使用不正确的调用约定,函数完成后堆栈的大小将与预期不同,从而导致此错误。

于 2013-07-11T17:51:06.680 回答