這是一個糟糕的例子,使用C運行庫DLL來調用puts。請繼續閱讀教程,因爲那裏有很好的信息,但是請嘗試製作Win32 API調用。
這是一個更好的介紹的P/Invoke:http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
這是老了,但信息還是不錯的。
編輯
我的解釋是錯誤的。
我去尋找一個正確的解釋,我發現C運行時放置方法和.NET框架Console.Write方法不同,他們如何寫入控制檯(Console.Write工作,其中p /調用put纔不是)。我想,也許答案是在那裏,所以我颳起了這個演示:
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
public static void Main()
{
int written;
string outputString = "Hello, World!\r\n";
byte[] outputBytes = Encoding.Default.GetBytes(outputString);
//
// This is the way the C-Runtime Library method puts does it
IntPtr conOutHandle = CreateFile("CONOUT$", 0x40000000, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
WriteConsole(conOutHandle, outputBytes, outputString.Length, out written, IntPtr.Zero);
//
// This is the way Console.Write does it
IntPtr stdOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
WriteFile(stdOutputHandle, outputBytes, outputBytes.Length, out written, IntPtr.Zero);
// Pause if running under debugger
if (Debugger.IsAttached)
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey();
}
}
const int STD_OUTPUT_HANDLE = -11;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int WriteFile(IntPtr handle, [In] byte[] bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
static extern bool WriteConsole(IntPtr hConsoleOutput, [In] byte[] lpBuffer, int nNumberOfCharsToWrite, out int lpNumberOfCharsWritten, IntPtr mustBeZero);
}
那些下調試成功輸出的兩個,即使啓用宿主進程。所以這是一個死路一條。
我想分享它,以防其導致其他人計算出爲什麼它發生 - Hans?
a)「不起作用」是什麼意思? b)PrintChar在做什麼/使用什麼? – 2010-11-21 20:24:57
「不起作用」的意思正是它所說的;該函數不執行它應該執行的任務,即寫入控制檯。它仍然會返回一個值,並且不會使程序崩潰;如果是這樣,我會記下這一點。 PrintChar(char c){putchar(c); } 就是這樣!它可以調試或不調試。 :) – ATC 2010-11-22 12:38:36