Re: Portability and marshalling integral data
On Nov 25, 11:45 am, "dragan" <spambus...@prodigy.net> wrote:
Brian wrote:
In the past there's been discussion about how using memcpy
to assist marshalling integral data should be avoided due to
portability reasons. From some very limited testing themore
portable approach that uses bit shifting to output/marshall
integral data is roughly 10 to 15% slower than using memcpy.
I'm wondering if it is possible to set things up so that the
more portable functions are used in a more limited way than
what I've seen suggested here. For example if a server has
both big endian and little endian (Intel) clients, would it
work to have the server send a "big endian" stream to the
big endian clients and a "little endian" stream to Intel
clients -- then both of those types of clients could use
memcpy to read/demarshall integral data types?
I believe it is possible to use memcpy without having
alignment problems. I know it is possible to show examples
of alignment problems using memcpy, but I don't think those
are relevant to marshalling of data structures that a
compiler has set up to it's liking.
What am I missing? Something to do with compiler flags?
What you are doing is specifying a protocol. IP, for example,
specifies (the wrong ;) ) byte order for packet information
and such, hence all those htonl-like macros.
There is no right or wrong (although I too prefer little
endian). IP is big endian because all of the backbones of the
network (where such protocols are developed) and the machines on
which large scale servers are run are all big endian. (Also,
htonl was an early hack, before all of the issues are
understood. I wouldn't expect to see it in modern code.)
If you say the spec is little endian, than whatever the other
end of the wire is doesn't matter: THEY have to convert the
incoming data to conform to your protocol specification.
Well, usually you negociate with your clients, and find a
consensus:-). But yes, there is (or should be) a protocol
specification which specifies exactly how an integral value
should be represented (byte order, but also size and
representation). And everyone has to convert incoming data to
conform to it, and generate it correctly in outgoing data.
There is more than just endianness to consider, of course. You
have to maintain the spec with what you send out by
controlling it with whatever you have to, like compiler
pragmas to control alignment and padding.
You typically can't control it enough just by flipping a few
compiler switches.
--
James Kanze