IStream CopyTo

Feb 6, 2012 at 3:51pm
I need help with the CopyTo method of ComTypes::IStream
I have the following code and there appears to be an issue where the original stream is left open.
Can someone please take a look and let me know what might be wrong with this code and if there is a better way to write this method?

Thanks!

const static int COPYTO_BUFFER_SIZE = 16384;
virtual void CopyTo(System::Runtime::InteropServices::ComTypes::IStream ^pstm, long long cb, System::IntPtr pcbRead, System::IntPtr pcbWritten)
{
array<unsigned char>^ buffer = gcnew array<unsigned char>(COPYTO_BUFFER_SIZE);
long long written = 0;

while(written < cb)
{
int count = min(COPYTO_BUFFER_SIZE, static_cast<int>(cb - written));

int read = stream->Read(buffer, 0, count);
if (read == 0) break;

pstm->Write(buffer, read, IntPtr::Zero);
written += read;
}

if (pcbRead != IntPtr::Zero) Marshal::WriteInt64(pcbRead, written);
if (pcbWritten != IntPtr::Zero) Marshal::WriteInt64(pcbWritten, written);
}
Feb 6, 2012 at 4:03pm
closed account (o1vk4iN6)
You make want to consider actually learning C++ ISO standard instead of that .net crap. May as well stick with one standard and use C# instead if your going to be using .net.
Feb 6, 2012 at 4:05pm
using .net is not option in this case
Feb 6, 2012 at 4:08pm
What do you mean "an issue"? I mean, why is it an issue for the stream to be left open? According to http://msdn.microsoft.com/en-us/library/windows/desktop/aa380038(v=vs.85).aspx , there is no specification that the original stream has to close after a call to CopyTo().

Also note that you should collect the actual number of bytes written in the destination stream (I think). Then use that value to increment your 'written' variable. Unless you know for sure that they are the same 100% of the time? I also think you should totalize the bytes read in a different variable so you don't "cheat" at the very end when you use 'written' for both output variables.

Other than that I don't think I see an issue, but then again, I don't know C++/CLI.
Feb 6, 2012 at 4:17pm
closed account (o1vk4iN6)
Dontmindme wrote:
using .net is not option in this case


You are using .net though, none of the libraries you are using here are C++ but are Microsoft's .net framework which are also accessible using C#. Except C# does not conflict with any established standards.
Last edited on Feb 6, 2012 at 4:17pm
Topic archived. No new replies allowed.