Skip to main content
gamedev.net
🔒 Locked

[.net] Filestream to chararray.

Started by The Parrot Nov 16, 2004 at 6:51 AM 1 replies 1k views
Original Post
The Parrot
The Parrot
Hi all, I got a very nasty problem; when I use filestream (or any other .NET interface, for that matters), it desires to use the managed version of Char-arrays. I'm trying to open a file as an array of bytes so I can pass it to an DirectX function, and a pointer to a managed char array is (obviously) not accepted. So could somebody please help me open a file into a non-managed array of bytes? Cheers, -Parrot
--Jeroen Stout - WebsiteCreator of-Divided
VizOne
VizOne
The solution depends on the language you use. In C#, a char[] means unicode characters, i.e. 16-bit per char. In C++/CLI or MC++ a char[] is 8 bit per character.

Here are some good starting points for several languages:

C#
static void Main() {    using ( Stream s = File.OpenRead( "filename.bla" ) ) {        // create buffer        byte[] buffer = new byte[s.Length];        // read whole file        s.Read( buffer, 0, buffer.Length );                // pin the buffer (GC won't move it anymore)        GCHandle handle = GCHandle.Alloc( buffer, GCHandleType.Pinned );        try {            // get the pointer to the first element            IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement( buffer, 0 );            // use ptr for DX Method (you might need to use ToPointer() etc.)        } finally {            // import: un-pin buffer!            handle.Free();        }    }}


C++/CLI
using namespace System;using namespace System::IO;using namespace stdcli::language;int main(){    Stream ^ stream = File::OpenRead("filename.bla");    try {        // create buffer        array<Byte> ^ buffer = gcnew array<Byte>(static_cast<int>(stream->Length));        // read whole file        stream->Read(buffer, 0, buffer->Length);        // get the pointer to the first element        pin_ptr<Byte> ptr = &buffer[0];        // cast to right type        char * ptrData = reinterpret_cast<char*>(ptr);        // use in DirectX    } finally{        stream->Close();    }}


MC++
using namespace System;using namespace System::IO;int main(){    Stream * stream = File::OpenRead("filename.bla");    try {        // create buffer        Byte buffer __gc[] = new Byte __gc[static_cast<int>(stream->Length)];        // read whole file        stream->Read(buffer, 0, buffer->Length);        // get the pointer to the first element        Byte __pin * ptr = &buffer[0];        // cast to right type        char * ptrData = reinterpret_cast<char*>(ptr);        // use in DirectX    } __finally{        stream->Close();    }}


Regards,
Andre

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.