调用C++开发的DLL报内存异常错误
问题:
最近开发的一个项目中使用了C++开发的一个MD5加密动态库,调用加密时传入的参数类型(string)不适合C++导致内存异常(虽然是偶尔出错,却导致IIS进程重启或退出)。现在修改传入参数类型为StringBuilder问题解决,现在发贴出来希望对遇到此问题的朋友有所帮助(这问题可把我给整惨了!)
原来的代码:
[DllImport("md5.DLL",CharSet=CharSet.Ansi, CallingConvention=CallingConvention.StdCall)]
public static extern void MD5ToStr(string inStr, int len, ref string outStr);
修改后的代码:
[DllImport("md5.DLL",CharSet=CharSet.Ansi, CallingConvention=CallingConvention.StdCall)]
public static extern void MD5ToStr(StringBuilder inStr, int len, ref StringBuilder outStr);
以下是在C++中的源码:
MD5DLL_API void MD5ToStr( const unsigned char* inStr, int inLen, char** outStr)
{
unsigned char result[16];
MD5_CTX context;
MD5Init (&context);
MD5Update (&context, (unsigned char*)inStr, inLen);
MD5Final ( result, &context);
BCD( result, 16, *outStr);
}