PInvoke function call unbalanced stack when turning on C DLL in C #

I wrote a C DLL and some C # code for testing, including this DLL and the execution of functions from it. I am not very good at this process and get a PInvokeStackImbalance exception when my DLL function is called from C # source code. The code is as follows (I commented on most of the code to isolate this problem):

C # inclusion code:

using System;
using System.Runtime.InteropServices;
using System.IO;

namespace TestConsoleGrids
{
    class Program
    {

        [DllImport("LibNonthreaded.dll", EntryPoint = "process")]
            public unsafe static extern void process( long high, long low);

        static void Main(string[] args)
        {
            System.Console.WriteLine("Starting program for 3x3 grid");

            process( (long)0, (long)0 );

            System.Console.ReadKey();
        }
    }
}

C ++ DLL Function Code

extern "C" __declspec(dllexport) void process( long high, long low );

void process( long high, long low )
{
    // All code commented out
}

Visual Studio generated the dllmain code (I do not understand this construct, so I enable it)

// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
      )
{
 switch (ul_reason_for_call)
 {
 case DLL_PROCESS_ATTACH:
 case DLL_THREAD_ATTACH:
 case DLL_THREAD_DETACH:
 case DLL_PROCESS_DETACH:
  break;
 }
 return TRUE;
}

Exception Details:

PInvoke 'TestConsoleGrids! TestConsoleGrids.Program:: process' . , , PInvoke . , PInvoke .

+3
3

. int MDA, Cdecl:

 [DllImport("LibNonthreaded.dll", CallingConvention = CallingConvention.Cdecl)]
 public static extern void process(int high, int low);

DLL-, C/++, .

+5

++ a long - 32 . # 64 . int #.

__stdcall ++. : __stdcall?

+2

in C # longmeans 64-bit int, and in C ++ long means 32-bit int, you need to change the pinvoke declaration to

 [DllImport("LibNonthreaded.dll", EntryPoint = "process")]
     public unsafe static extern void process( int high, int low);

You can also try changing your C ++ declaration to stdcall, which is the calling convention used by most exported functions in a Windows environment.

 __stdcall  __declspec(dllexport) void process( long high, long low );
0
source

Source: https://habr.com/ru/post/1733691/


All Articles