把文件读到内存中然后使用内存加载

  • 把文件读到内存中然后使用内存加载

分两种方式实现C++和C

 

001. int read_dll_memory_load (TCHAR str_dll_path[],char str_export_fun[]) //用C++的方式把文件读到内存加载
002.
003. filebuf *pbuf; 
004. ifstream filestr; 
005. long size; 
006. char * buffer; 
007.  
008. filestr.open (str_dll_path, ios::binary); // 要读入整个文件,必须采用二进制打开 
009.  
010. pbuf=filestr.rdbuf(); // 获取filestr对应buffer对象的指针  
011.  
012. size=pbuf->pubseekoff (0,ios::end,ios::in);  // 调用buffer对象方法获取文件大小
013. pbuf->pubseekpos (0,ios::in); 
014.  
015. buffer=new char[size];  // 分配内存空间
016.  
017. pbuf->sgetn (buffer,size);  // 获取文件内容
018.  
019. filestr.close(); 
020.  
021. HMEMORYMODULE module=MemoryLoadLibrary(buffer);//从内存中加载文件
022.  
023. FARPROC mc=MemoryGetProcAddress(module, str_export_fun);
024.  
025. if (mc==NULL)
026. {
027. OutputDebugStringA("MemoryGetProcAddress NULL");
028.  
029. return 0;
030. }
031.  
032. typedef int (WINAPI* FN_Execute) (int nType);
033.  
034. FN_Execute execute=(FN_Execute)mc;
035.  
036. execute(0);
037.  
038. MemoryFreeLibrary(module);
039.  
040. delete []buffer; 
041.  
042. return 0; 
043. }
044.  
045. UINT read_dll_memory_load_c(TCHAR str_dll_path[],char str_export_fun[])
046. {
047. HANDLE hFile = CreateFile(str_dll_path, GENERIC_READ , 0, NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
048.  
049. if (hFile==NULL||hFile==INVALID_HANDLE_VALUE)
050. {
051. return 0;
052. }
053.  
054. DWORD  dwFileSize= 0;
055.  
056. dwFileSize=GetFileSize(hFile,  NULL);
057.  
058. CloseHandle(hFile);
059.  
060. char * buff=new char[dwFileSize];
061.  
062. FILE* fp = _tfopen(str_dll_path, _T("rb"));
063.  
064. if (fp)
065. {
066. dwFileSize=fread(buff, 1, dwFileSize, fp);
067. }
068.  
069. fclose(fp);
070.  
071.  
072. HMEMORYMODULE hm=MemoryLoadLibrary(buff);
073.  
074. if (hm==NULL)
075. {
076. return 0;
077. }
078.  
079. FARPROC mc=MemoryGetProcAddress(hm, str_export_fun);
080.  
081. if (mc==NULL)
082. {
083. OutputDebugStringA("MemoryGetProcAddress NULL");
084.  
085. return 0;
086. }
087.  
088. typedef int (WINAPI* FN_Execute) (int nType);
089.  
090. FN_Execute execute=(FN_Execute)mc;
091.  
092. execute(0);
093.  
094. MemoryFreeLibrary(hm);
095.  
096. delete []buff; 
097.  
098. return 0;
099. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值