Win32中CInternetSession运行异常(afxCurrentAppName 为空)

来源:互联网 发布:博士后 知乎 编辑:程序博客网 时间:2024/06/07 02:12

CInternetSession--wininet库

最近在做一个小任务,其中有一项功能是获取网页源码,VC中可以用CInternetSession来实现,以下为从MSDN摘下来的

CInternetSession session; CHttpFile* file = NULL; file = (CHttpFile *)session.OpenURL(_T("http://www.microsoft.com")); if (NULL != file){//Do something here with the web request//Clean up the file here to avoid a memory leak!!!!!!!file->Close(); delete file; }session.Close(); 


编译后运行显示错误:

Debug Assertion failed!
program:test.exe
file:afxwin1.inl
line:27

跟踪到afxwin1.inl文件的第27行是

{ ASSERT(afxCurrentAppName != NULL); return afxCurrentAppName; }

这里说明是AfxCurrentAppName为空造成的问题;

解决办法:
CWinApp app((LPCTSTR)argv[0]);
app.InitApplication();

AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);

如果argv[0]基本常识普及,请参考以下:

C/C++语言中的main函数,经常带有参数argc,argv,如下: int main(int argc, char** argv)int main(int argc, char* argv[])这两个参数的作用是什么呢?argc 是指命令行输入参数的个数,argv存储了所有的命令行参数。假如你的程序是hello.exe,如果在命令行运行该程序,(首先应该在命令行下用 cd 命令进入到 hello.exe 文件所在目录) 运行命令为: hello.exe Shiqi Yu那么,argc的值是 3,argv[0]是"hello.exe",argv[1]是"Shiqi",argv[2]是"Yu"。 下面的程序演示argc和argv的使用: #include <stdio.h>int main(int argc, char ** argv){int i;for (i=0; i < argc; i++)printf("Argument %d is %s.\n", i, argv[i]);return 0;}假如上述代码编译为hello.exe,那么运行 hello.exe a b c d e将得到 Argument 0 is hello.exe.Argument 1 is a.Argument 2 is b.Argument 3 is c.Argument 4 is d.Argument 5 is e.运行 hello.exe lena.jpg将得到 Argument 0 is hello.exe.Argument 1 is lena.jpg.


分析:在win32程序中调用MFC中的类


#include <stdio.h>#include <afxinet.h>#include <afx.h>#include <afxwin.h>int main(int argc, char **argv){    CWinApp app((LPCTSTR)argv[0]);    app.InitApplication();    AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);    CInternetSession session;     CHttpFile* file = NULL;     file = (CHttpFile *)session.OpenURL(_T("http://www.microsoft.com"));     if (NULL != file)    {        //Do something here with the web request        //Clean up the file here to avoid a memory leak!!!!!!!        file->Close();         delete file;     }    session.Close();     return 0;}

1 0
原创粉丝点击