C# 中dllimport 应用

C#中得DllImpor

大家在实际工作学习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);
}

 

 

---------------------------------------------------------------

 

(2)关于unsigned char * pBuffer,这个unsigned char *其实有2个转换可选,有时可以使用byte[],有时则是StringBuilder,这就要集体问题具体分析了。例如:

 

int GetErrorMessage_ex6 (int ErrorNr, unsigned long BufLen, unsigned char* pBuffer);

void copy_buffer_ex6 (unsigned char * pTargetBuffer, unsigned char *pSourceBuffer, unsigned long Amount);

  前者就转换成StringBuilder后者是byte[]。

  (3)有些变量虽是整型但是可以用枚举,而且用枚举感觉更合适

  例如

int db_read_ex6 (unsigned short BlkNr, unsigned char DatType, unsigned

short StartNr, unsigned long * pAmount, unsigned long BufLen, unsigned

char * pReadBuffer, unsigned long * pDatLen)中,unsigned char DatType其实指的是“0x02 = BYTE, 0x04 = WORD, 0x06 = DWORD default: DatType = 0x02”等数据类型

,因此可以翻译成

public enum DatType : byte//PLC数据类型

        {

            BYTE = 0x02,

            WORD = 0x04,

            DWORD = 0x06,

        }

  (4)对了,如果是对象型的引用,比如unsigned char*转成byte[],是不需要加ref,但如果是c++ int转 c# int 则要加ref关键字。

  要说明的就是这些,下面请各位看官看看我的转换代码吧,还请见教:

    public class Prodave6

    {

        #region 常值定义(用于极限值)

        public const int MAX_CONNECTIONS = 64; // 64 is default in PRODAVE

        public const int MAX_DEVNAME_LEN = 128;// e.g. "S7ONLINE"

        public const int MAX_BUFFERS = 64; // 64 for blk_read() and blk_write()

        public const int MAX_BUFFER = 65536; // Transfer buffer for error text)

        #endregion

        #region 结构体定义

        public struct CON_TABLE_TYPE//待连接plc地址属性表

        {

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]

            //public CON_ADR_TYPE Adr; // connection address

            public byte[] Adr; // connection address

            // MPI/PB station address (2)

            // IP address (192.168.0.1)

            // MAC address (08-00-06-01-AA-BB)

            public byte AdrType; // Type of address: MPI/PB (1), IP (2), MAC (3)

            public byte SlotNr; // Slot number

            public byte RackNr; // Rack number

        }

        public enum DatType : byte//PLC数据类型

        {

            BYTE = 0x02,

            WORD = 0x04,

            DWORD = 0x06,

        }

        public enum FieldType : byte//PLC区域类型

        {

            //Value types as ASCII characters区域类型对应的ASCII字符

            //data byte (d/D)

            d = 100,

            D = 68,

            //input byte (e/E)

            e = 101,

            E = 69,

            //output byte (a/A)

            a = 97,

            A = 65,

            //memory byte (m/M)

            m = 109,

            M = 77,

            //timer word (t/T),

            t = 116,

            T = 84,

        }

        #endregion

        #region PLC基本函数

        [DllImport("Prodave6.dll")]//连接PLC操作

        //参数:连接号(0-63)、常值"S7ONLINE"、待连接plc地址属性表长度(字节为单位,常值9)、待连接plc地址属性表

        public extern static int LoadConnection_ex6(int ConNr, string pAccessPoint, int ConTableLen, ref  CON_TABLE_TYPE pConTable);

        [DllImport("Prodave6.dll")]//断开PLC操作

        //参数:连接号(0-63)

        public extern static int UnloadConnection_ex6(UInt16 ConNr);

        [DllImport("Prodave6.dll")]//激活PLC连接操作

        //参数:连接号(0-63)

        public extern static int SetActiveConnection_ex6(UInt16 ConNr);

        [DllImport("Prodave6.dll")]//PLC db区读取操作

        //参数:data block号、要读取的数据类型、起始地址号、需要读取类型的数量、缓冲区长度(字节为单位)、缓冲区、缓冲区数据交互的长度

        public extern static int db_read_ex6(UInt16 BlkNr, DatType DType, UInt16 StartNr, ref UInt32 pAmount, UInt32 BufLen,

            byte[] pBuffer, ref UInt32 pDatLen);

        [DllImport("Prodave6.dll")]//PLC db区写入操作

        //参数:data block号、要写入的数据类型、起始地址号、需要写入类型的数量、缓冲区长度(字节为单位)、缓冲区

        public extern static int db_write_ex6(UInt16 BlkNr, DatType Type, UInt16 StartNr, ref UInt32 pAmount, UInt32 BufLen,

            byte[] pBuffer);

        [DllImport("Prodave6.dll")]//PLC 任意区读取操作

        //参数:要读取的区类型、data block号(DB区特有,默认为0)、起始地址号、需要读取类型的数量、

        //缓冲区长度(字节为单位)、缓冲区、缓冲区数据交互的长度

        public extern static int field_read_ex6(FieldType FType, UInt16 BlkNr, UInt16 StartNr, UInt32 pAmount, UInt32 BufLen,

            byte[] pBuffer, ref UInt32 pDatLen);

        [DllImport("Prodave6.dll")]//PLC 任意区写入操作

        //参数:要写入的区类型、data block号(DB区特有,默认为0)、起始地址号、需要写入类型的数量、

        //缓冲区长度(字节为单位)、缓冲区

        public extern static int field_write_ex6(FieldType FType, UInt16 BlkNr, UInt16 StartNr, UInt32 pAmount, UInt32 BufLen,

            byte[] pBuffer);

        [DllImport("Prodave6.dll")]//PLC M区某字节的某位读取操作

        //参数:M区字节号、位号、当前的值(0/1)

        public extern static int mb_bittest_ex6(UInt16 MbNr, UInt16 BitNr, ref int pValue);

        [DllImport("Prodave6.dll")]//PLC M区某字节的某位写入操作

        //参数:M区字节号、位号、要写入的值(0/1)

        public extern static int mb_setbit_ex6(UInt16 MbNr, UInt16 BitNr, byte Value);

        #endregion

        #region PLC200用数据传输函数

        [DllImport("Prodave6.dll")]//200系列PLC 任意区读取操作

        //参数:要读取的区类型、data block号(DB区特有,默认为0)、起始地址号、需要读取类型的数量、

        //缓冲区长度(字节为单位)、缓冲区、缓冲区数据交互的长度

        public extern static int as200_field_read_ex6(FieldType FType, UInt16 BlkNr, UInt16 StartNr, UInt32 pAmount, UInt32 BufLen,

            byte[] pBuffer, ref UInt32 pDatLen);

        [DllImport("Prodave6.dll")]//200系列PLC 任意区写入操作

        //参数:要写入的区类型、data block号(DB区特有,默认为0)、起始地址号、需要写入类型的数量、

        //缓冲区长度(字节为单位)、缓冲区

        public extern static int as200_field_write_ex6(FieldType FType, UInt16 BlkNr, UInt16 StartNr, UInt32 pAmount, UInt32 BufLen,

            byte[] pBuffer);

        [DllImport("Prodave6.dll")]//200系列PLC M区某字节的某位读取操作

        //参数:M区字节号、位号、当前的值(0/1)

        public extern static int as200_mb_bittest_ex6(UInt16 MbNr, UInt16 BitNr, ref int pValue);

        [DllImport("Prodave6.dll")]//200系列PLC M区某字节的某位写入操作

        //参数:M区字节号、位号、要写入的值(0/1)

        public extern static int as200_mb_setbit_ex6(UInt16 MbNr, UInt16 BitNr, byte Value);

        #endregion

        #region PLC数据转换函数

        [DllImport("Prodave6.dll")]//诊断错误信息操作

        //参数:错误代号、缓冲区大小(字节为单位)、缓冲区

        public extern static int GetErrorMessage_ex6(int ErrorNr, UInt32 BufLen, [MarshalAs(UnmanagedType.LPStr)] StringBuilder pBuffer);

        [DllImport("Prodave6.dll")]//S7浮点数转换成PC浮点数

        //参数:S7浮点数、PC浮点数

        public extern static int gp_2_float_ex6(UInt32 gp, ref float pieee);

        [DllImport("Prodave6.dll")]//PC浮点数转换成S7浮点数

        //参数:PC浮点数、S7浮点数

        public extern static int float_2_gp_ex6(float ieee, ref UInt32 pgp);

        [DllImport("Prodave6.dll")]//检测某字节的某位的值是0或1

        //参数:字节值、位号

        public extern static int testbit_ex6(byte Value, int BitNr);

        [DllImport("Prodave6.dll")]//检测某字节的byte值转换成int数组

        //参数:byte值、int数组(长度为8)

        public extern static void byte_2_bool_ex6(byte Value, int[] pBuffer);

        [DllImport("Prodave6.dll")]//检测某字节的int数组转换成byte值

        //参数:int数组(长度为8)

        public extern static byte bool_2_byte_ex6(int[] pBuffer);

        [DllImport("Prodave6.dll")]//交换数据的高低字节——16位数据

        //参数:待交换的数据

        public extern static UInt16 kf_2_integer_ex6(UInt16 wValue);//16位数据——WORD

        [DllImport("Prodave6.dll")]//交换数据的高低字节——32位数据

        //参数:待交换的数据

        public extern static UInt32 kf_2_long_ex6(UInt32 dwValue);//32位数据——DWORD

        [DllImport("Prodave6.dll")]//交换数据缓冲区的的高低字节区,例如pBuffer[0]与pBuffer[1],pBuffer[2]与pBuffer[3]交换

        //参数:待交换的数据缓冲区,要交换的字节数,如Amount=pBuffer.Length,则交换全部缓冲

        public extern static void swab_buffer_ex6(byte[] pBuffer, UInt32 Amount);

        [DllImport("Prodave6.dll")]//复制数据缓冲区

        //参数:目的数据缓冲区,源数据缓冲区,要复制的数量(字节为单位)

        public extern static void copy_buffer_ex6(byte[] pTargetBuffer, byte[] pSourceBuffer, UInt32 Amount);

        [DllImport("Prodave6.dll")]//把二进制数组传换成BCD码的数组——16位数据

        //参数:要处理的数组,要处理的字节数,转换前是否先交换高低字节,转换后是否要交换高低字节

        //InBytechange为1则转换BCD码之前,先交换高低字节

        //OutBytechange为1则转换BCD码之后,再交换高低字节

        //如果InBytechange和OutBytechange都没有置1,则不发生高低位的交换

        //16位数据BCD码值的许可范围是:+999 —— -999

        public extern static void ushort_2_bcd_ex6(UInt16[] pwValues, UInt32 Amount, int InBytechange, int OutBytechange);//16位数据——WORD

        [DllImport("Prodave6.dll")]//把二进制数组传换成BCD码的数组——32位数据

        //参数:要处理的数组,要处理的字节数,转换前是否先交换高低字节,转换后是否要交换高低字节

        //InBytechange为1则转换BCD码之前,先交换高低字节

        //OutBytechange为1则转换BCD码之后,再交换高低字节

        //如果InBytechange和OutBytechange都没有置1,则不发生高低位的交换

        //32位数据BCD码值的许可范围是:+9 999 999 —— -9 999 999

        public extern static void ulong_2_bcd_ex6(UInt32[] pdwValues, UInt32 Amount, int InBytechange, int OutBytechange);//32位数据——DWORD

        [DllImport("Prodave6.dll")]//把BCD码的数组传换成二进制数组——16位数据

        //参数:要处理的数组,要处理的字节数,转换前是否先交换高低字节,转换后是否要交换高低字节

        //InBytechange为1则转换BCD码之前,先交换高低字节

        //OutBytechange为1则转换BCD码之后,再交换高低字节

        //如果InBytechange和OutBytechange都没有置1,则不发生高低位的交换

        //16位数据BCD码值的许可范围是:+999 —— -999

        public extern static void bcd_2_ushort_ex6(UInt16[] pwValues, UInt32 Amount, int InBytechange, int OutBytechange);//16位数据——WORD

        [DllImport("Prodave6.dll")]//把BCD码的数组传换成二进制数组——32位数据

        //参数:要处理的数组,要处理的字节数,转换前是否先交换高低字节,转换后是否要交换高低字节

        //InBytechange为1则转换BCD码之前,先交换高低字节

        //OutBytechange为1则转换BCD码之后,再交换高低字节

        //如果InBytechange和OutBytechange都没有置1,则不发生高低位的交换

        //32位数据BCD码值的许可范围是:+9 999 999 —— -9 999 999

        public extern static void bcd_2_ulong_ex6(UInt32[] pdwValues, UInt32 Amount, int InBytechange, int OutBytechange);//32位数据——DWORD

        [DllImport("Prodave6.dll")]//查看64个连接中哪些被占用,哪些已经建立

        //参数:传输缓冲的字节长度,64位长度的数组(0或1)

        public extern static void GetLoadedConnections_ex6(UInt32 BufLen, int[] pBuffer);

        #endregion

        #region 自定义辅助函数

        public  static UInt16 bytes_2_word(byte dbb0, byte dbb1)//将高低2个byte转换成1个word

        {

            UInt16 dbw0;

            dbw0 = (UInt16)(dbb0 * 256 + dbb1);

            return dbw0;

        }

        public static UInt32 bytes_2_dword(byte dbb0, byte dbb1, byte dbb2, byte dbb3)//将高低4个byte转换成1个dword

        {

            UInt32 dbd0;

            dbd0 = (UInt32)(dbb0 *16777216 + dbb1 * 65536 + dbb2 * 256 + dbb3);

            return dbd0;

        }

        public static UInt32 words_2_dword(UInt16 dbw0, UInt16 dbw2)//将高低2个word转换成1个dword

        {

            UInt32 dbd0;

            dbd0 = (UInt32)(dbw0 * 65536 + dbw2);

            return dbd0;

        }

        public static byte[] word_2_bytes(UInt16 dbw0)//将word拆分为2个byte

        {

            byte[] bytes = new byte[2];

            bytes[0] = (byte)(dbw0 / 256);

            bytes[1] = (byte)(dbw0 % 256);

            return bytes;

        }

        public static byte[] dword_2_bytes(UInt32 dbd0)//将dword拆分为4个byte

        {

            byte[] bytes = new byte[4];

            bytes[0] = (byte)(dbd0 / 16777216);

            dbd0 = dbd0 % 16777216;

            bytes[1] = (byte)(dbd0 / 65536);

            dbd0 = dbd0 % 65536;

            bytes[2] = (byte)(dbd0 / 256);

            bytes[3] = (byte)(dbd0 % 256);

            return bytes;

        }

        public static UInt16[] dword_2_words(UInt32 dbd0)//将dword拆分为2个word

        {

            UInt16[] words = new UInt16[2];

            words[0] = (UInt16)(dbd0 / 65536);

            words[1] = (UInt16)(dbd0 % 65536);

            return words;

        }

        #endregion

   

    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值