mardi 25 juillet 2017

Need a better understanding of smart pointers with windows API

I'm having a hard time understanding smart pointers (still in the beginning stages of learning tbh). Maybe I've been starring at the problem too long and I'm missing the easy concept...

I'm in the process of turning all my "new/deletes" into smart pointers so I don't have such a big issue with memory leaks/corruption.

I'm aware unique_ptr's can only have one ownership at a time. I'm assuming that means you can't alter data in a variable without having ownership. (Please correct me if I'm wrong) So instead, I'm passing a raw shared_ptr to get the address of bytes I need to look into PE Headers. pFileBase will have the bytes "MZ" but my shared_ptr is not coming back with those bytes. What am I missing?

Is there a way to have WinAPI functions return into a smart pointer? I'm also aware my shared_ptr is not char[] so that is my next step on fixing.

`BOOL InitializeFromDisk(std::wstring &wsTempPath, char *pFileBase)
{
 ...
 pFileBase = (PCHAR)MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
 if (pFileBase == 0) return FALSE;
 return TRUE;
}
int main()
{
 std::shared_ptr<char> pFile = std::make_shared<char>(0);
 InitializeFromDisk(L"c:\\...", pFile.get());
 ...
 PIMAGE_DOS_SIGNATURE pDosHdr;
 memcpy_s(pDosHdr, strlen(pFile.get()), &pFile, strlen(pFile.get())); //I'm sure this line doesn't quit work yet 
}`

Aucun commentaire:

Enregistrer un commentaire