在将C DLL包含到C#中时,对PInvoke函数的调用使堆栈不平衡
发布时间:2020-12-16 09:26:27 所属栏目:百科 来源:网络整理
导读:我编写了一个C DLL和一些C#代码来测试包含这个DLL并从中执行函数.我对这个过程并不太熟悉,每当从C#源代码调用DLL函数时,我都会收到PInvokeStackImbalance异常.代码如下(我已经评论了大多数代码来隔离这个问题): C#包含代码: using System;using System.Run
我编写了一个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:
[DllImport("LibNonthreaded.dll",CallingConvention = CallingConvention.Cdecl)] public static extern void process(int high,int low); 这不是导出的DLL函数的标准调用约定,如果可以,您可以考虑在C/C++代码中更改它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |