[英]Download image from HTTP request triggering a breakpoint
我正在嘗試使用 Win32 從 URL 將圖像下載到用戶的桌面上。 我已經處理了所有 HTTP 請求的東西,並且知道它一切正常。 當我 go 調用CreateFile()
時,Visual Studios 調試器只會說“異常:Application.exe 已觸發斷點”並且它將在 CreateFile() 行上恢復。 還有一個錯誤代碼“檢測到嚴重錯誤c0000374”
這是我的代碼:
VARIANT varResponse;
VariantInit(&varResponse);
...
hr = pIWinHttpRequest->get_ResponseBody(&varResponse);
...
if (SUCCEEDED(hr)) {
long upperBounds;
long lowerBounds;
unsigned char* buff;
//Make sure that varResponse is an array of unsigned bytes
if (varResponse.vt == (VT_ARRAY | VT_UI1)) {
long Dims = SafeArrayGetDim(varResponse.parray);
//It should only have one dimension
if (Dims == 1) {
//Get Array lower and upper bounds
SafeArrayGetLBound(varResponse.parray, 1, &lowerBounds);
SafeArrayGetUBound(varResponse.parray, 1, &upperBounds);
upperBounds++;
SafeArrayAccessData(varResponse.parray, (void**)&buff);
HANDLE hFile;
DWORD dwBytesWritten;
PWSTR filepath[MAX_PATH];
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &*filepath);
if (SUCCEEDED(hr)) {
//PathCombine(filepathForImage, filepathToDesktop, L"\\todaysDailyImage.jpg");
PathAppend(*filepath, L"todaysDailyImage.jpg");
MessageBox(NULL, *filepath, L"Check if filepath works", MB_OK);
}
hFile = CreateFile(*filepath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
//File failed
}
else {
WriteFile(hFile, buff, upperBounds - lowerBounds, &dwBytesWritten, NULL);
//File was written
}
CloseHandle(hFile);
CoTaskMemFree(filepath);
SafeArrayUnaccessData(varResponse.parray);
MessageBox(NULL, L"Everything was cleaned up", L"Update:", MB_OK);
}
}
}
我做錯什么了嗎?
您使用文件filepath
的方式都是錯誤的。
您將其聲明為MAX_PATH
(260) 個PWSTR
指針的數組。
當您僅通過名稱引用數組時,您最終會得到指向數組第一個元素的指針。 因此, &*filepath
與&*(&filepath[0])
相同,實際上是&filepath[0]
。 並且*filepath
與*(&filepath[0])
相同,實際上是filepath[0]
。 所以,就SHGetKnownFolderPath()
和MessageBox()
而言,它們只對數組中的第一個PWSTR
指針進行操作,而忽略其他 259 個數組元素。 那部分還可以,但是很浪費。
但是, PathAppend()
需要一個目標緩沖區,該緩沖區是一個包含MAX_PATH
個WCHAR
元素的數組。 您將附加到SHGetKnownFolderPath()
分配為其 output 的WCHAR[]
數組,該數組不足以容納您嘗試將 append 分配給它的文件名。 因此,您正在觸發錯誤,因為您正在嘗試修改尚未分配用於保存該修改的 memory。
您根本不需要PWSTR
數組。 嘗試更多類似的東西:
PWSTR folderpath;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &folderpath);
if (FAILED(hr)) {
// ...
}
else {
PWSTR filepath;
hr = PathAllocCombine(folderpath, L"todaysDailyImage.jpg", 0, &filepath);
if (FAIlED(hr)) {
// ...
}
else {
MessageBoxW(NULL, filepath, L"Check if filepath works", MB_OK);
hFile = CreateFileW(filepath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
//File failed
}
else {
WriteFile(hFile, buff, upperBounds - lowerBounds, &dwBytesWritten, NULL);
//File was written
CloseHandle(hFile);
}
LocalFree(filepath);
}
CoTaskMemFree(folderpath);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.