You don't have to open the file to read the mapped data, you just have to
call OpenFileMapping followed by a call to MapViewOfFile(Ex).
MapViewOfFile can be called with an offset(low and high) of 0 and a
numberOfBytesToMap = 0, this will map the memory starting from offset 0 to
the end of the section. The sending side could pass a structure (marshaled
to unmanaged memory) like this:
struct MyData {
int size;
byte[] data;
}
where MyData.data is the serialized MemoryStream and MyData.size is the size
in bytes of the serialized stream. The 'reading' side uses the size value to
copy 'size' bytes from unmanaged memory (data) to a managed byte array that
can be wrapped by a MemoryStream to be deserialized by a binary formatter.
Willy.
| Hmm - yes, you're absolutely right. I was using some generic routines I'd
got
| off the web. I've spent some time understanding them and writing my own
| specific code now, and I can indeed serialise to the MemoryStream first
and
| get the length from that.
| However, I do have a couple of problems: I'm using a MemoryMappedFile and
a
| couple of events for IPC. Now, writing the file in process 1 is no
problem,
| as above, but I'm having trouble getting process 2 to read the file.
| Problem 1: when I open the file by calling CreateFileMapping with both
| length parameters set to zero I get an error 87 - ERROR_INVALID_PARAMETER.
| Acxcording to the documentation setting zero length should open an
existing
| file with its existing length. If I force it by setting the low-order
length
| arbitrarily to 1024 it's fine.
| Problem 2: having forced the open, I then find I can't get the actual
| length: GetFileSize() returns INVALID_FILE_SIZE.
| Any suggestions on either or both problems would be most welcome.
| --
| Dave
|
|
| "Willy Denoyette [MVP]" wrote:
|
| >
| > | > |I am serialising an object to a memory mapped file (using the
| > | CreateFileMapping and MapViewOfFile p/invoke calls). These need to
know
| > the
| > | maximum size of the "file". I can put in a "good guess" ie it won't be
| > more
| > | than, say, 1K, but it would be tidier to use the actaul size. Is it
| > actually
| > | possible to find out how big an object (or even better, a class) would
be
| > | when it is serialised (I suppose one way would be to separately
serialise
| > it
| > | to a memory stream and get the size of the memory stream, but would
that
| > be
| > | accurate? It's certainly not very efficient.)
| > | --
| > | Dave
| >
| > You'll have serialize the object to a MemoryStream anyway, why do you
| > consider this as being inefficient?
| >
| > Willy.
| >
| >
| >