我编写了一个C DLL和一些C#代码来测试包含这个DLL并从中执行函数.我对这个过程并不太熟悉,每当从C#源代码调用DLL函数时,我都会收到PInvokeStackImbalance异常.代码如下(我已经评论了大多数
C#包含代码:
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函数代码
extern "C" __declspec(dllexport) void process( long high, long low ); void process( long high, long low ) { // All code commented out }
Visual Studio生成了dllmain代码(我不明白这个构造,所以我包括它)
// 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; }
例外的细节是:
调用约定是错误的.如果删除int参数不会使MDA跳闸,那么它就是Cdecl:A call to PInvoke function ‘TestConsoleGrids!TestConsoleGrids.Program::process’ 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.
[DllImport("LibNonthreaded.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void process(int high, int low);
这不是导出的DLL函数的标准调用约定,如果可以,您可以考虑在C/C++代码中更改它.