最近搞几个PInvoke几个DLL, 在.net 2.0下木有问题, 跑的很好
如下:
[DllImport( "tjo.dll" )]
private static extern int zd_init( int port );
[DllImport( "tjo.dll" )]
private static extern int zd_exit( int port );
[DllImport( "tjo.dll" )]
private static extern int zd_reset( int port );
但是到了4.0下的话出现了堆栈不对称的情况 ,对 PInvoke 函数...的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。
开始一直以为是头文件的问题, 后来发现示例很好,没有问题, 换到2.0下同样的OK, 最后发现声明改一下就好了,如下
[DllImport("tjo.dll", EntryPoint = "zd_beep",CallingConvention=CallingConvention.Cdecl)]
private static extern int zd_beep(int icdev, int buzztime, char times, char Type);
[DllImport("tjo.dll", EntryPoint = "zd_exit", CallingConvention = CallingConvention.Cdecl)]
private static extern int zd_exit(int port);
[DllImport("tjo.dll", EntryPoint = "zd_init", CallingConvention = CallingConvention.Cdecl)]
private static extern int zd_init(int port);
[DllImport("tjo.dll", EntryPoint = "zd_reset", CallingConvention = CallingConvention.Cdecl)]
private static extern int zd_reset(int port);
改成调用方清理堆栈即可.