2011-02-11 59 views
2

我有以下使用DLLImport的C#代碼。PInvoke代碼在C#中的使用情況

using System; 

namespace LvFpga { 
    class RegTest 
    { 

    [DllImport("kernel32")]  
    public extern static int LoadLibrary(string lpLibFileName); 
    [DllImport("kernel32")]  
    public extern static bool FreeLibrary(int hLibModule); 

    public static bool IsDllRegistered(string DllName)  
    {  
     int libId = LoadLibrary(DllName); 
     if (libId>0) FreeLibrary(libId); 
     return (libId>0);  
    } 
    public static void Main(string[] args) 
    { 
     Console.WriteLn(IsDllRegistered("msdia100.dll")); 
    } 
    } 
} 

當我只是運行csc CSCODE.cs我得到了錯誤。

regtest.cs(7,6): error CS0246: The type or namespace name 'DllImport' could not be found (are you 
     missing a using directive or an assembly reference?) 
regtest.cs(7,6): error CS0246: The type or namespace name 'DllImportAttribute' could not be found 
     (are you missing a using directive or an assembly reference?) 
regtest.cs(9,6): error CS0246: The type or namespace name 'DllImport' could not be found (are you 
     missing a using directive or an assembly reference?) 
regtest.cs(9,6): error CS0246: The type or namespace name 'DllImportAttribute' could not be found 
     (are you missing a using directive or an assembly reference?) 

怎麼了?可能會添加什麼選項?

+0

您需要在使用System之後添加'using System.Runtime.InteropServices;`; – 2011-02-11 14:30:20

回答

7

你必須有

using System.Runtime.InteropServices; 

此外,沒有功能 「Console.WriteLn」。您需要

Console.WriteLine(IsDllRegistered("msdia100.dll")); 
3

您在代碼的開頭缺少using System.Runtime.InteropServices;

3

把這個在文件的頂部:

using System.Runtime.InteropServices; 

你的聲明是錯誤的,這將不會在64位操作系統上運行。從pinvoke.net網站獲取正確的。還要添加錯誤檢查,SetLastError屬性。