调用方法和步骤:
首先,要添加命名空间:
using System.Runtime.InteropServices;
这个命名空间主页是为了使用:[DllImport]
第二,要静态引用外部库:
方法,要在类内,方法外。同时通过 static extern 声明。示例代码如下:
[DllImport("ticketPrinterDll.dll",CharSet=CharSet.Unicode)]
public static extern void ShowMessage( );
private void button1_Click(object sender, EventArgs e)
{
ShowMessage();
}
最后,调用函数。这个就不用说了。直接调用就OK了。
[DllImport]的基本语法和属性:
[DllImport("dll name")]
EntryPoint:使用其它函数名
CharSet 指示用在入口点中的字符集,如:CharSet=CharSet.Ansi;
SetLastError 指示方法是否保留 Win32"上一错误",如:SetLastError=true;
ExactSpelling 指示 EntryPoint 是否必须与指示的入口点的拼写完全匹配,如:ExactSpelling=false;
PreserveSig指示方法的签名应当被保留还是被转换, 如:PreserveSig=true;
CallingConvention指示入口点的调用约定, 如:CallingConvention=CallingConvention.Winapi;
例如:传染的字符集为Unicode
[DllImport("ticketPrinterDll.dll",CharSet=CharSet.Unicode)]
全部代码如下:
using System;
using System.Collections.Generic;
using https://www.wendangku.net/doc/0017633856.html,ponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TestDllCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("ticketPrinterDll.dll",CharSet=CharSet.Unicode)]
public static extern void ShowMessage( );
private void button1_Click(object sender, EventArgs e)
{
ShowMessage();
}
}
}