当前位置: 首页 > 编程语言 > C#

in.Net4-PInvokeStackImbalanceexception分享

时间:2023-04-10 16:45:27 C#

in.Net4:PInvokeStackImbalanceexception我在.Net3.5的项目中使用了msvcrt.dll中的strlen函数。更进一步:privateunsafestaticexternintstrlen(byte*pByte);迁移到.NET4.0后,如果我使用此函数,则会抛出PInvokeStackImbalanceexception。如何导入.NET3.5msvcrt.dll或修复此异常?我怀疑问题出在调用约定上,您应该使用Cdecl。[DllImport("msvcrt.dll",CallingConvention=CallingConvention.Cdecl)]privateunsafestaticexternintstrlen(byte*pByte);这不是一个直接的答案,但似乎对于这样的函数,编写你自己的.例如,以下C#代码可能有效(尽管使用现有函数的衬垫也可能有效):staticintmystrlen(byte[]pbyte){inti=0;while(pbyte[i]!=0)i++;返回我;从.NET3.5到4应该没有变化。(顺便说一下,msvcrt.dll不是框架的一部分——它是MicrosftC++运行时库)。您确定项目中没有其他任何更改吗?我刚刚尝试了这段代码,它按预期工作并打印出“4”:classTest{publicunsafestaticvoidMain(string[]args){byte[]bytes=newbyte[]{70,40,30,51,0};fixed(byte*ptr=bytes){intlen=strlen(ptr);控制台.WriteLine(len);}}[DllImport("msvcrt.dll")]privateunsafestaticexternintstrlen(byte*pByte);我不确定您为什么要从托管代码调用strlen,但当然您可能有自己的理由。如果您需要替代托管实现,可以使用以下内容:privatestaticintmanaged_strlen(byte[]bytes){returnbytes.TakeWhile(b=>b!=0).Count();}当然,这个涉及的字节(unicode)字符不多,但我不认为strlen也会这样做。纯娱乐:以上就是C#学习教程的全部内容:in.Net4:PInvokeStackImbalanceexception。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——publicstaticunsafeintstrlen(void*buffer){byte*end=(byte*)buffer;while(*end++!=0);返回(int)结束-(int)缓冲区-1;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: