C# 调用C++ DLL提示“尝试读取或写入受保护的内存。”
我要用C#调用C++的DLL(里面是关于DES加密的算法),但是调用是有时会报错提示“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
C#调用的代码:
[DllImport("TestDll.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern string desEncrypt2(string keyText, string plainText);
C++代码:
char *desEncrypt2(char *encryptedText, const char *plainText)
{
unsigned char buf[9];
char hex[17];
unsigned char longbuf[512+1];
char longhex[512*2+1];
memset(buf, 0, sizeof(buf));
memset(hex, 0, sizeof(hex));
memset(longbuf, 0, sizeof(longbuf));
memset(longhex, 0, sizeof(longhex));
strncpy((char *)longbuf, plainText, sizeof(longbuf)-1); //平台移植到2008的需要,strncpy->strncpy_s
int index;
for (index = 0; longbuf[index]; index += 8)
{
memcpy(buf, longbuf+index, 8);
DesEncrypt(key, buf);
for (int i=0; i < 8; i++)
sprintf(hex+2*i, "%02x", buf[i]);
memcpy(longhex+2*index, hex, 16);
}
strcpy(encryptedText, longhex);
return encryptedText;
}
很可能是strcpy(encryptedText, longhex);这句导致的,但是去掉直接返回longhex又是乱码。
我在网上找了很久,有说分配的内存空间没有释放,请问“unsigned char longbuf[512+1];char longhex[512*2+1];”,这两个要释放的吗?不是动态分配啊,我不大懂C++麻烦各位帮忙了。
另外,我用的是VS2010的平台