How to get windows directory using unsafe code with pointer and unmanaged function from DLL in C#

1 Answer

0 votes
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe uint GetWindowsDirectory(byte* lpBuffer, uint uSize);

        // Error CS0227  Unsafe code may only appear if compiling with /unsafe 
        /*
            Open the project Properties page
            Click the Build property page
            Select the Allow Unsafe Code check box
        */
        static unsafe void Main(string[] args)
        {
            byte[] array = new byte[512];

            unsafe
            {
                fixed (byte *p = array)GetWindowsDirectory(p, 512);
            }
            ASCIIEncoding ae = new ASCIIEncoding();

            Console.WriteLine(ae.GetString(array));
        }
    }
}


/*
run:

C:\Windows

*/

 



answered Apr 28, 2017 by avibootz

Related questions

1 answer 3,976 views
1 answer 184 views
1 answer 101 views
2 answers 232 views
232 views asked Apr 28, 2017 by avibootz
...