C# DllImport的用法

大家在实际工作学习C#的时候,可能会问:为什么我们要为一些已经存在的功能(比如Windows中的一些功能,C++中已经编写好的一些方法)要重新编写代码,C#有没有方法可以直接都用这些原本已经存在的功能呢?答案是肯定的,大家可以通过C#中的DllImport直接调用这些功能。
DllImport所在的名字空间 using System.Runtime.InteropServices;
MSDN中对DllImportAttribute的解释是这样的:可将该属性应用于方法。DllImportAttribute 属性提供对从非托管 DLL 导出的函数进行调用所必需的信息。作为最低要求,必须提供包含入口点的 DLL 的名称。
DllImport 属性定义如下:
namespace System.Runtime.InteropServices
{
  [AttributeUsage(AttributeTargets.Method)]
  public class DllImportAttribute: System.Attribute
  {
   public DllImportAttribute(string dllName) {...}
   public CallingConvention CallingConvention;
   public CharSet CharSet;
   public string EntryPoint;
   public bool ExactSpelling;
   public bool PreserveSig;
   public bool SetLastError;
   public string Value { get {...} }
  }
}
  说明:
  1、DllImport只能放置在方法声明上。
  2、DllImport具有单个定位参数:指定包含被导入方法的 dll 名称的 dllName 参数。
  3、DllImport具有五个命名参数:
   a、CallingConvention 参数指示入口点的调用约定。如果未指定 CallingConvention,则使用默认值 CallingConvention.Winapi。
   b、CharSet 参数指示用在入口点中的字符集。如果未指定 CharSet,则使用默认值 CharSet.Auto。
   c、EntryPoint 参数给出 dll 中入口点的名称。如果未指定 EntryPoint,则使用方法本身的名称。
   d、ExactSpelling 参数指示 EntryPoint 是否必须与指示的入口点的拼写完全匹配。如果未指定

  • 0
    点赞
  • 123
    收藏
    觉得还不错? 一键收藏
  • 41
    评论
C#中,DllImport用于引入非托管dll中的方法(函数),而不是数据(变量)。要在C#中使用DllImport,需要遵循以下步骤: 1. 引入命名空间:在代码文件的顶部,使用using语句引入System.Runtime.InteropServices命名空间。 2. 创建函数声明:使用DllImport属性来声明要引入的函数。例如,使用\[DllImport("demo.dll")\] public static extern bool OpenDemo();来声明一个名为OpenDemo的函数,该函数位于名为demo.dlldll文件中。 3. 提供dll的名称:至少需要提供包含入口点的dll的名称。可以在DllImport属性中使用EntryPoint参数来指定入口点的名称。 4. 可选参数:DllImport属性还有其他可选参数,如CallingConvention、CharSet、ExactSpelling、PreserveSig和SetLastError,用于指定入口点的调用约定、字符集、是否必须与指定的入口点拼写完全一致等。 需要注意的是,DllImport只能放置在方法声明上,并且被DllImport属性修饰的方法必须具有extern修饰符。 希望以上信息对您有所帮助。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *2* *3* [C#DllImport使用方法详解](https://blog.csdn.net/niudongling/article/details/120416823)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 41
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值