调用wcsncat时遇到的诡异问题

guanzhouxuezi 2014-02-18 11:58:20
问题是这样的。
在C#代码中调用了C++的dll
C#调用:
 [DllImport("Assist.dll", EntryPoint = "SetXMLTextInEncryptFileConfig", CallingConvention = CallingConvention.Cdecl)]
public static extern void SetXMLTextInEncryptFileConfig(string strEncryptFilePath, String pszDomain, String pszKey, Int32 pos, [MarshalAs(UnmanagedType.LPWStr)]String tag, [MarshalAs(UnmanagedType.LPWStr)]String content);


public void SetXMLTextInConfigInfo(string pszDomain, string pszKey, int pos, string tag, string content)
{
SetXMLTextInEncryptFileConfig(Path_ConfigInfo, pszDomain, pszKey, pos, tag, content);

}


C++实现
void SetXMLTextInEncryptFileConfig(char* strEncryptFilePath,char* pszDomain, char* pszKey, size_t pos, wchar_t *tag, wchar_t *content)
{
CString EncryptFilePath = strEncryptFilePath;
CString strDomain = pszDomain;
CString strKey = pszKey;
CSimpleRefCnt<CEncryptFiles> pSPEncryptFile = qqmusic::GetEncryptFile(EncryptFilePath);
wchar_t *pWValue;
if(pSPEncryptFile.IsValid())
{
if(!pSPEncryptFile->GetValueAsString(strDomain,strKey,&pWValue))
{
return;
}
int nWValueLen = wcslen(pWValue);
wchar_t *pCValue = new wchar_t[nWValueLen*2];
ZeroMemory(pCValue, nWValueLen*2);
wchar_t *pHead = new wchar_t[pos];
ZeroMemory(pHead, pos);
printf("pWValue is %ls", pWValue);
wcsncpy(pHead, pWValue, pos);
printf("pHead is %ls", pHead);
wchar_t *pTail;
pTail = wcsstr(pWValue, tag);
wcsncat(pCValue,pHead, pos);
wcscat(pCValue,L"\n");
wcscat(pCValue,content);
wcscat(pCValue,L"\r\n");
int n = wcslen(content);
wcscat(pCValue,pTail);
wcscat(pCValue,L"\0");

string configString = pSPEncryptFile->SetValue(strDomain,strKey,pCValue);

CEncryptFile* pEncryptFile = new CEncryptFile();
pEncryptFile->SaveDat(strEncryptFilePath,configString);
delete[] pHead;
delete[] pCValue;
delete pEncryptFile;
}
}


C#代码运行的时候提示“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”
单步联调的时候发现走到C++代码的
wcsncat(pCValue,pHead, pos);
这一行时,就挂掉了。
哪位高手帮忙看看怎么回事儿
...全文
79 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
mjp1234airen4385 2014-02-18
  • 打赏
  • 举报
回复
wcsncat(pCValue,pHead, pos); 你看看pCValue和pHead连接和的长度是不是超过了pCValue定义的长度.
guanzhouxuezi 2014-02-18
  • 打赏
  • 举报
回复
前面传错了值。。。
guanzhouxuezi 2014-02-18
  • 打赏
  • 举报
回复
汗,是我搞错了

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧