jump to navigation

Having fun with Pinvoke April 30, 2009

Posted by gcorbin in .NET, C#.
Tags: ,
add a comment

The .Net libraries have many built-in objects that can be used to create most types of programs for windows. In most cases, the typical developer would not need anything more. However, there are a few cases in which a direct call to a COM object is needed. The ability to call objects that are not .Net from within .Net is called Interoperability. InterOp calls are often used in cases where a .Net program needs to communicate with older software that is based on COM. It can also be used to make direct calls to the windows Kernel. In these cases, a common term among .Net developers is the Pinvoke. Using a Pinvoke is very similar to calling a Windows API from VB6. You need to copy the declaration and import the library and then you can use it. The compiler sees code that uses Pinvoke as being unsafe code. This means that you will need to set the project properties for your code to allow compile unsafe code. The declarations and constants used for these calls can all be found at http://www.pinvoke.net/. Some sample .Net code that uses a Pinvoke can be seen below. This code is using the Windows Kernel to create a file.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace CreateFilewithPinInvoke

{

    class FileReader

    {

        const uint GENERIC_READ = 0×80000000;

        const uint FILE_ALL_ACCESS = 0×80000000;

        const uint OPEN_EXISTING = 3;

        const uint OPEN_ALWAYS = 3;

        System.IntPtr handle;

 

        [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]

        static extern unsafe System.IntPtr CreateFile

        (

            string FileName,          // file name

            uint DesiredAccess,       // access mode

            uint ShareMode,           // share mode

            uint SecurityAttributes,  // Security Attributes

            uint CreationDisposition, // how to create

            uint FlagsAndAttributes,  // file attributes

            int hTemplateFile         // handle to template file

        );

 

        [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]

        static extern unsafe bool CloseHandle

        (

            System.IntPtr hObject // handle to object

        );

 

        public bool Open(string FileName)

        {

            // open the existing file for reading      

            handle = CreateFile(FileName,FILE_ALL_ACCESS,0,0, OPEN_ALWAYS,0,0);

 

            if (handle != System.IntPtr.Zero)

                return true;

            else

                return false;

        }

 

        public bool Close()

        {

            return CloseHandle(handle);

        }

    }

 

    class Program

    {

        static int Main(string[] args)

        {

            if (args.Length != 1)

            {

                System.Console.WriteLine(“Usage : CreateFile.exe <FileName>”);

                return 1;

            }

  

            FileReader fr = new FileReader();

 

            if (fr.Open(args[0]))

            {

                System.Console.WriteLine(“Created requested file”);

                return 0;

            }

            else

            {

                System.Console.WriteLine(“Failed to create file!”);

                return 1;

            }

        }

    }

}

-Enjoy.

Follow

Get every new post delivered to your Inbox.