How to use DllImport

WebKit 内核编译 WebKit内核编译实在是一项折磨人的事情,虽然webkit.org官方有一个文档,但是有时候机器本身配置环境还是和教程有差别。 经过三天三夜平均每天2点钟的奋斗,今天终于搞定了。 其实,官方的描述已经非常到位,只要保证每一步都执行了,差别应该不大,需要多加处理的就是本机实际环境导致的具体问题。 首先按照官方文档进行操作 http://www.webkit.org/buil 阅读详情

大家在实际工作学习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 是否必须与指示的入口点的拼写完全匹配。如果未指定 ExactSpelling,则使用默认值 false。
   e、PreserveSig 参数指示方法的签名应当被保留还是被转换。当签名被转换时,它被转换为一个具有 HRESULT 返回值和该返回值的一个名为 retval 的附加输出参数的签名。如果未指定 PreserveSig,则使用默认值 true。
   f、SetLastError 参数指示方法是否保留 Win32"上一错误"。如果未指定 SetLastError,则使用默认值 false。
  4、它是一次性属性类。
  5、此外,用 DllImport 属性修饰的方法必须具有 extern 修饰符。

DllImport的用法:
DllImport("MyDllImport.dll")]
private static extern int mySum(int a,int b);

一 在C#程序设计中使用Win32类库
常用对应类型:
1、DWORD 是 4 字节的整数,因此我们可以使用 int 或 uint 作为 C# 对应类型。
2、bool 类型与 BOOL 对应。

示例一:调用 Beep() API 来发出声音
Beep() 是在 kernel32.lib 中定义的,在MSDN 中的定义,Beep具有以下原型:
BOOL Beep(DWORD dwFreq, // 声音频率
DWORD dwDuration // 声音持续时间);
用 C# 编写以下原型:
[DllImport("kernel32.dll")]
public static extern bool Beep(int frequency, int duration);

示例二:枚举类型和常量
MessageBeep() 是在 user32.lib 中定义的,在MSDN 中的定义,MessageBeep具有以下原型:
BOOL MessageBeep(UINT uType // 声音类型
);

用C#编写一下原型:
public enum BeepType
{
  SimpleBeep = -1,
  IconAsterisk = 0x00000040,
  IconExclamation = 0x00000030,
  IconHand = 0x00000010,
  IconQuestion = 0x00000020,
  Ok = 0x00000000,
}
uType 参数实际上接受一组预先定义的常量,对于 uType 参数,使用 enum 类型是合乎情理的。
[DllImport("user32.dll")]
public static extern bool MessageBeep(BeepType beepType);

示例三:处理结构
有时我需要确定我笔记本的电池状况。Win32 为此提供了电源管理函数,搜索 MSDN 可以找到GetSystemPowerStatus() 函数。
BOOL GetSystemPowerStatus(
  LPSYSTEM_POWER_STATUS lpSystemPowerStatus
);
此函数包含指向某个结构的指针,我们尚未对此进行过处理。要处理结构,我们需要用 C# 定义结构。我们从非托管的定义开始:
typedef struct _SYSTEM_POWER_STATUS {
BYTE  ACLineStatus;
BYTE  BatteryFlag;
BYTE  BatteryLifePercent;
BYTE  Reserved1;
DWORD BatteryLifeTime;
DWORD BatteryFullLifeTime;
} SYSTEM_POWER_STATUS, *LPSYSTEM_POWER_STATUS;
   然后,通过用 C# 类型代替 C 类型来得到 C# 版本。
struct SystemPowerStatus
{
  byte ACLineStatus;
  byte batteryFlag;
  byte batteryLifePercent;
  byte reserved1;
  int batteryLifeTime;
  int batteryFullLifeTime;
}
这样,就可以方便地编写出 C# 原型:
[DllImport("kernel32.dll")]
public static extern bool GetSystemPowerStatus(
  ref SystemPowerStatus systemPowerStatus);
   在此原型中,我们用“ref”指明将传递结构指针而不是结构值。这是处理通过指针传递的结构的一般方法。
   此函数运行良好,但是最好将 ACLineStatus 和 batteryFlag 字段定义为 enum:
  enum ACLineStatus: byte
   {
    Offline = 0,
    Online = 1,
    Unknown = 255,
   }
   enum BatteryFlag: byte
   {
    High = 1,
    Low = 2,
    Critical = 4,
    Charging = 8,
    NoSystemBattery = 128,
    Unknown = 255,
   }
请注意,由于结构的字段是一些字节,因此我们使用 byte 作为该 enum 的基本类型

示例四:处理字符串


二 C# 中调用C++代码
int 类型
[DllImport(“MyDLL.dll")]
//返回个int 类型
public static extern int mySum (int a1,int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int a2,int b2)
{
//a2 b2不能改变a1 b1
//a2=..
//b2=...
return a+b;
}

//参数传递int 类型
public static extern int mySum (ref int a1,ref int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int *a2,int *b2)
{
//可以改变 a1, b1
*a2=...
*b2=...
return a+b;
}


DLL 需传入char *类型
[DllImport(“MyDLL.dll")]
//传入值
public static extern int mySum (string astr1,string bstr1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr2,char * bstr2)
{
//改变astr2 bstr 2 ,astr1 bstr1不会被改变
return a+b;
}


DLL 需传出char *类型
[DllImport(“MyDLL.dll")]
// 传出值
public static extern int mySum (StringBuilder abuf, StringBuilder bbuf );
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr,char * bstr)
{
//传出char * 改变astr bstr -->abuf, bbuf可以被改变
return a+b;
}

DLL 回调函数

BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)

using System;
using System.Runtime.InteropServices;
public delegate bool CallBack(int hwnd, int lParam); //定义委托函数类型
public class EnumReportApp
{
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);
public static void Main() {
CallBack myCallBack = new CallBack(EnumReportApp.Report); EnumWindows(myCallBack, 0);
}
public static bool Report(int hwnd, int lParam)
{
Console.Write("Window handle is ");
Console.WriteLine(hwnd); return true;
}
}

DLL 传递结构
BOOL PtInRect(const RECT *lprc, POINT pt);

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}
[StructLayout(LayoutKind.Explicit)]
public struct Rect
{
[FieldOffset(0)] public int left;
[FieldOffset(4)] public int top;
[FieldOffset(8)] public int right;
[FieldOffset(12)] public int bottom;
}
Class XXXX {
[DllImport("User32.dll")]
public static extern bool PtInRect(ref Rect r, Point p);
}

Unity中使用自定义Attribute Attribute是c#的语言特性 msdn说明如下: The Attribute class associates predefined system information or user-defined custom information with a target element. A target element can be an assembly, class, constru... 阅读详情

相关推荐

多个dll互相调用的完美实现

delphi多个dll互相调用,有别于Exe调用dll,特别是存在窗口的dll的程序中...................!

C# dllimport

一、DllImport是System.Runtime.InteropServices命名空间下的一个属性类,其功能是提供从非托管DLL导出的函数的必要调用信息 DllImport的定义如下: public class DllImportAttribute:System.Attribute {   public DllImportAttribute(string dllNam

june905206961的专栏 3350

C#与C调用C++Dll,非托管,含struct调用及enum公用,完整项目,可直接编译或运行

C#与C调用C++,非托管,含struct调用及enum公用,完整项目,可直接编译或运行。 项目将所有工程的输出统一到Debug。 vs2015+Framework4.6,注意工程的配置。 所有东西自写,只是出于样例参考的作用,所以代码规范性见谅。

C#中DllImport用法和路径问题

C# 中DllImport的使用以及如何确定dll调用的路径

weixin_40314351的博客 1万+

人工势场法在自动驾驶避障中的实践与优化

本文深入探讨了人工势场法在自动驾驶避障中的核心原理与实践优化。通过解析引力与斥力模型,揭示了经典算法在局部最优和目标不可达等问题上的局限性,并重点介绍了改进斥力场函数、引入道路边界斥力及动态参数调整等关键优化策略,有效提升了该局部路径规划算法在复杂动态场景下的实用性与鲁棒性。

weixin_29208327的博客 924

什么是OAuth 2.0?

OAuth2.0是一种授权协议而非登录协议,核心思想是通过令牌(Token)而非密码实现安全授权。它涉及三个关键角色:用户、第三方应用和身份提供商(IdP)。最常用的授权码流程(AuthorizationCode Flow)通过浏览器三方对话,确保用户密码只提供给IdP而非第三方应用。OAuth2.0提供四种授权方式,其中授权码和客户端凭证是当前主流,而隐式和密码模式已不推荐。需要注意的是,OAuth2.0解决的是授权问题,身份认证需通过OpenID Connect实现。该协议通过临时令牌机制,实现了&qu

sonadorje的专栏 1151

How to Use Attributes in C#

How to Use Attributes in C# Introduction Usinng an attribute is a way to add special meaning to our method and cause it to act in ...

didan3807的博客 183

uniapp(全端兼容) - 最新详细实现支付键盘功能组件,从底部弹出数字键盘输入支付密码进行付款交互效果,自定义支付密码键盘仿微信、支付宝支付键盘,1~9密码数字键盘,电商支付(详细示例代码复制运行

uniapp,微信小程序,自定义数字键盘,输入支付密码的键盘组件,uniapp小程序如何实现从底部弹出输入支付密码自定义键盘功能,uniapp小程序密码支付键盘组件插件,自定义数字键盘输入页面,怎么封装底部弹窗自定义数字键盘用于输入支付密码,uniapp小程序仿类似电商支付密码输入模态框,uniapp微信小程序平台实现自定义支付密码键盘,uniapp 密码支付,数字键盘,安全键盘,交易键盘,交易密码,交易密码输入框,uniapp自定义支付键盘: uniapp自定义支付键盘,uniapp小程序端实现键盘输入支

✅ 精选推荐文章 2904

How to use GCC to build DLL by DEF file in MinGW?

Howto use GCC to build DLL by DEF file in MinGW?The “How togenerate DLL files by GCC in the MinGW” has described how to generate DLLfile by the declaring prefix(__declspec( dllexport ) or __de

燕青专栏 3370

从零开始之驱动发开、linux驱动(七、字符驱动之led最终版)

我们上一接用的gpiolib非常杂乱,使用了两种 1.各硬件厂商实现的,如s3c_gpio_cfgpin(S5PV210_GPJ0(5), S3C_GPIO_SFN(1)) 2.系统公共的,如gpio_set_value(S5PV210_GPJ0(4),val) 其实公共的也是对各硬件厂商的封装,用那个都可以,个人建议用系统公共的,应为这样换芯片厂商,不影响任何使用。   2.错误处理基...

To_run_away的博客 2386

Allan方差这个工具,怎么把它用的更顺手?(附Allan方差、动态Allan方差代码)

本文详细说明了Allan方差和动态Allan方差的计算过程,并通过递归运算和时间序列选择两种算法提高动态Allan方差的计算效率。文末提供了快速动态Allan方差计算代码。

victoryqian528的博客 372

How To Bind C++ Code with Dotnet Core

How To Bind C++ Code with Dotnet Core While you are working with compiled code, you often find yourself in the situation that every bit of performance count (just think about GPU intensive operations...

tytok的专栏 441

基于高德地图的单车路径规划与绘制实战(Vue3 + TypeScript)【拓展:货车路径规划函数、限行检测、城市 Adcode】

✅ 支持单辆车路径规划✅ 自动绘制路线✅ 起点、终点、途经点标注✅ 自动缩放视野至全路径✅ 获取路线距离、时长、过路费✅ 提供清除功能✅ 路线信息保存至本文完整实现了一个基于高德地图 JS SDK + Vue3 + TypeScript的👉单车路径规划与绘制模块。核心亮点:清晰的结构;灵活的扩展性;实时路线信息记录(🚀 你可以很方便地将本模块集成到车联网、调度监控、地图展示类项目中。❤️ 如果这篇文章对你有帮助,别忘了:评论区交流 💬。

专注于前端开发与实战技巧,记录从零到一的学习与项目经验。分享 Vue3 / JavaScript / TypeScript / Flutter /Uniapp等前端技术,以及 性能优化、工程化、最佳实践。 1264

How to avoid C# console applications from closing automatically.

One way is to interop it with msvcrt.dll You can pinvoke this C function into your C# application. This process is very easy. There are a few steps: 1) Insert System.Runtime.InteropServi...

aylx27880的博客 134

ROCm rocr-libhsakmt分析系列1-2:多GPU跨卡VRAM访问机制分析

本文基于ROCr-Runtime的libhsakmt库源码,深入分析了多GPU系统中跨设备内存访问的实现机制。主要内容包括: 实现流程概述:通过P2P拓扑发现、统一虚拟地址空间、页表映射和硬件转发四个步骤,实现零拷贝的跨GPU内存访问。

图形/计算GPU的驱动与虚拟化技术分享园地 2498

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

c# - P/Invoke, DllImport, Marshal Structures and Type conversions

P/Invoke as in the following quote provides basically the way to calls into the unmanaged DLLs. the quote is as follow.  MSDN 写道 P/Invoke is short for Platform Invoke and provides the functionality...

iteye_13882的博客 226

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

How to import dll in c# that can be accessed by [DllImport]

The steps are as follows:1. Compile your C# DLL (You may use Visual Studio for this).2. Decompile your C# DLL using ILDASM.EXE.3. Expose/Export your methods (Details to follow).4. Recompile your C# DL...

weixin_34406796的博客 119

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

How to customize the console applicaton

下面是如何最大化console和改变其显示的字体颜色的代码,顺便包含了计时代码(帮助做性能分析): class Program { [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GetConsoleWindow(); ...

weixin_30699443的博客 95

Call Unmanaged Code. Part 1 - Simple DLLImport

Call Unmanaged Code. Part 1 - Simple DLLImportBy Vyacheslav Biktagirov Managed world is beautiful, I have all classes I want in FrameWork.. But what if I want call

i-mimi 742

HOW TO:获取ExcelApplication COM对象的进程

Author:水如烟 代码Option Strict OffImports System.Runtime.InteropServicesPublic Class ExcelDemo    Private gApplication As Object    Private gProcess As Process    Public ReadOnly Property Applicatio

水如烟 2013

DLLImport

namespace Wintellect.Interop.Sound { using System; using System.Runtime.InteropServices; using System.ComponentModel; sealed class Sound { public static void M...

weixin_34075551的博客 121

C#动态调用系统DLL函数的类(不使用DllImport)

using System;using System.Runtime.InteropServices;using System.Reflection;using System.Reflection.Emit;public class DllCaller : IDisposable{ [DllImport("Kernel32.dll")] static extern IntPtr Lo...

weixin_30505225的博客 168

c# char unsigned,C#编组的char **和unsigned char型**

Here is the problem - i have some C image processing library that i need to use from C# application. Lack of experience with DllImport strikes me hard for now.The function i need to use looks like:IMA...

weixin_42516575的博客 861

How to take a screenshot of a control with a scroll bar?

using System.Runtime.InteropServices; using System; using System.Drawing; using System.Windows.Forms; namespace JHEMR.JHOODCariesRecord { public class ControlImage { #region API ...

ZhuangLiang 223

Call Unmanaged DLLs from C#

导读:   Download the code for this article:CQA0208.exe (47 KB)   QHow do I call a DLL or Win32 API function from my C# code if the function has a string (char*) output parameter? I can pass a string

onioncong的programer生活 1732
上一篇: Reflection conclusion
下一篇: 写点基础
xyjnufop
博客等级 码龄19年 10粉丝 99原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值