Csharp/CSharp Tutorial/Windows/DllImport — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 12:20, 26 мая 2010

API File reader

using System;
using System.Runtime.InteropServices;
using System.Text;
    class APIFileReader
    {
        uint GenericRead = 0x80000000;
        uint OpenExisting = 3;
        uint UseDefault = 0;
        int fileHandle;
        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe int CreateFile(string filename,uint desiredAccess,uint shareMode,uint attributes,uint creationDisposition,uint flagsAndAttributes,uint templateFile);
        [DllImport("kernel32", SetLastError = true)]
        static extern unsafe bool ReadFile(int hFile,void* lpBuffer,int nBytesToRead,int* nBytesRead,int overlapped);
        public APIFileReader(string filename)
        {
            fileHandle = CreateFile(filename,GenericRead, UseDefault, UseDefault, OpenExisting,UseDefault, UseDefault); 
        }
        public unsafe int Read(byte[] buffer, int index, int count)
        {
            int bytesRead = 0;
            fixed (byte* bytePointer = buffer)
            {
                ReadFile(fileHandle, bytePointer + index, count, &bytesRead, 0); 
            }
            return bytesRead;
        }
    }
    class Test
    {
        public static void Main()
        {
            APIFileReader fileReader = new APIFileReader("data.txt");
            int BuffSize = 128;
            byte[] buffer = new byte[BuffSize];
            ASCIIEncoding asciiEncoder = new ASCIIEncoding();
            while (fileReader.Read(buffer, 0, BuffSize) != 0)
            {
                Console.Write("{0}", asciiEncoder.GetString(buffer));
            }
        }
    }

DllImport

using System;
using System.Runtime.InteropServices;
class MainClass
{
  [DllImport("user32.dll", CharSet = CharSet.Auto)]
  public static extern int MessageBox(int hWnd, String text, String caption, uint type);
  [STAThread]
  static void Main(string[] args)
  {
    MessageBox(0, "Hello World", "MyBox", 1);
  }
}

DllImport: load dll library

using System;
using System.Runtime.InteropServices;
public sealed class MainClass
{
    [DllImport("kernel32.dll")]
    static extern IntPtr HeapCreate(uint flOptions, UIntPtr dwInitialSize,UIntPtr dwMaximumSize);
    [DllImport("kernel32.dll")]
    static extern bool HeapDestroy(IntPtr hHeap);
    public static void Main() {
        IntPtr theHeap = HeapCreate( 0, (UIntPtr) 4096, UIntPtr.Zero );
        HeapDestroy( theHeap );
        theHeap = IntPtr.Zero;
    }
}

External Method

using System;
using System.Text;
using System.Runtime.InteropServices;
class MainClass
{
   [DllImport("kernel32", SetLastError = true)]
   public static extern int GetCurrentDirectory(int a, StringBuilder b);
   static void Main()
   {
      StringBuilder sb = new StringBuilder();
      sb.Length = 250;
      GetCurrentDirectory(250, sb);
      Console.WriteLine(sb);
   }
}

Get address of a method from Dll

using System;
using System.Threading;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
    class Program
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr LoadLibrary(string dllName);
        [DllImport("kernel32.dll")]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
        delegate int MessageBoxDelegate(IntPtr hwnd,
            [MarshalAs(UnmanagedType.LPWStr)]string text,
            [MarshalAs(UnmanagedType.LPWStr)]string caption,
            int type);
        static void Main(string[] args)
        {
            IntPtr userApi = LoadLibrary("user32.dll");
            IntPtr msgBoxAddress = GetProcAddress(userApi, "MessageBoxW"); // unicode (wide) message box
            MessageBoxDelegate mbd = (MessageBoxDelegate)Marshal.GetDelegateForFunctionPointer(msgBoxAddress,typeof(MessageBoxDelegate));
            mbd(IntPtr.Zero, "A", "B", 0);
            DoSomething(mbd);
        }
        static void DoSomething(MessageBoxDelegate mbd)
        {
            mbd(IntPtr.Zero, "Work completed.", "Work Progress", 0);
        }
    }