PInvoke code usage in C#

倾然丶 夕夏残阳落幕 提交于 2019-12-08 02:41:17

问题


I have the following C# code that uses DLLImport.

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"));
    }
  }
}

When I simply run csc CSCODE.cs I got the errors.

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?)

What's wrong? What might be added in options?


回答1:


You have to have

using System.Runtime.InteropServices;

Moreover, there is no function "Console.WriteLn". You need

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



回答2:


You are missing a using System.Runtime.InteropServices; at the beginning of the code.




回答3:


Put this at the top of the file:

 using System.Runtime.InteropServices;

Your declarations are wrong, this won't work on a 64-bit operating system. Get the right ones from the pinvoke.net website. Also add error checking, SetLastError property.



来源:https://stackoverflow.com/questions/4970106/pinvoke-code-usage-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!