简体   繁体   English

无法将C#int传递给非托管C ++ DLL

[英]can't pass C# int to unmanaged C++ DLL

I am new to interfacing a C# .exe project to native Visual-C++ DLL. 我是新的将C#.exe项目连接到本机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". 我无法弄清楚如何传递一个简单的整数,以下代码导致弹出错误“PInvoke ...不平衡堆栈”。

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

 extern "C"
 {

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

C# ....................... 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);
     }

You need to add CallingConvention = CallingConvention.Cdecl to your DllImport like so: 您需要将CallingConvention = CallingConvention.Cdecl添加到您的DllImport如下所示:

[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. VS2010之前的编译器假设CallingConvention.Cdecl但从那以后你必须添加它,除非你调用其中一个Win32 API。

pm100 is correct. pm100是正确的。 You need to tell the p/invoke marshaller that the function is using C declaration (as opposed to StdCall, which is default). 您需要告诉p / invoke marshaller该函数正在使用C声明(而不是StdCall,这是默认值)。 Inside the DllImport attribute, add the following parameter: CallingConvention = CallingConvention.Cdecl 在DllImport属性中,添加以下参数: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. 如果使用不正确的调用约定,则在函数完成后,堆栈的大小将与预期的大小不同,从而导致此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM