c++visual-studio-2015runtime-errorurlmon

How to fix "Run-Time Check Failure #0" error when trying to download a file with urlmon.dll?


I have written a downloader program in C++ using urlmon.dll.

I have used Visual Studio 2015 RTM as the IDE.

Here are my codes:

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include "clocale"
#include "fstream"
#include "iostream"
#include "string"
using namespace std;

typedef int*(*tdDosyaIndir)(void*, char*, char*, DWORD, void*);

int main()
{
setlocale(LC_ALL, "turkish");

string strAdres;

cout << "İndirilecek adresi girin:\n";
cin >> strAdres;

HINSTANCE dll = LoadLibrary(L"urlmon.dll");
tdDosyaIndir DosyaIndir = (tdDosyaIndir)GetProcAddress(dll, "URLDownloadToFileA");

DosyaIndir(0, &strAdres[0u], "dosya.html", 0, 0);

FreeLibrary(dll);

return 0;
}

But the problem is when I try to download something program shows this error:

screenshot of dialog box

What should I do in order to fix this issue?


Solution

  • You need to specify the calling convention in the function pointer typedef.

    Windows API functions generally use the __stdcall calling convention. However, C and C++ functions typically use the __cdecl calling convention, and that is the compiler's default. When there is a mismatch of the calling convention, the compiler generates the wrong code, and you get this error message.

    To ensure the compiler generates the correct code to call the function, your typedef for it should look like this:

    typedef HRESULT (__stdcall *tdDosyaIndir)(void*, char*, char*, DWORD, void*);