• Welcome to Valhalla Legends Archive.
 

MapViewOfFile API

Started by BinaryzL, May 29, 2004, 11:23 AM

Previous topic - Next topic

BinaryzL

I am a little confused on this one. Since in C++:
lpdwBuffer = (LPDWORD) MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
It looks like it makes the variable into an array or something, because If I try printf("%d\n",lpdwBuffer[0]); before the API it crashes but If I do printf("%d\n",lpdwBuffer[0]); or whatever index/element after the API lpdwBuffer and that element is set to a value and works.

Is there code for doing this in VB or is this API doing something else?

AntiFlame

First of all, you were asking why it crashes.  The reason is because before you make the call to MapViewOfFile lpdwBuffer is an uninitialized pointer.  Attempting to read from the (likely) random address that it points to before using MapViewOfFile to give it a valid pointer will cause an access violation.

As to whether or not you can use memory mapped files from Visual Basic, the answer is yes and no.  You can certainly map a file into your address space, but without either copying the mapped file into a String for manipulation (defeating the purpose of having the mapping in the first place) you'll find yourself doing a lot of painful workarounds to try to emulate the pointer arithmetic and access of mapped file data that you can get in C/C++.

BinaryzL

I have seen some code examples in vb that use MapViewOfFile and use the CopyMemoryRead API to load it into a type.

Adron

However, if you're going to copy the memory to your own buffer anyway, you might as well just ReadFile from the start instead of memory mapping the file.

BinaryzL

Yeah I suppose, but is there somewhere that explains what MapViewOfFile does better than MSDN does?

Adron

MapViewOfFile maps a view of a file into your address space.

This means that a certain region from a file will suddenly just "be there" in your memory. In a language (such as C++) that supports pointers, you would be familiar with memory addresses and how to access them. In VB, you don't deal with pointers, and so you may not have the necessary background to be able to understand this function. It's no big deal though, since the function isn't very useful to a VB programmer.

I'm not sure how to explain it in VB terms, since VB doesn't have pointers. It's like a string/array variable that is really the file itself, i.e. it doesn't exist separate from the file. An assignment to it will write to the file, and a read from it will read the file. The whole file also isn't read into memory at once, rather on demand, as you access the memory.

Eric

#6
Wouldn't opening the file for Binary Access Read be about the equivalent?

Adron

Quote from: LoRd[nK] on June 12, 2004, 10:02 PM
Wouldn't opening the file for Binary Access Read be about the equivalent?

It would be about equivalent to CreateFile + ReadFile. It wouldn't be the same as MapViewOfFile.