首 页 网络编程
网页制作 图形图象 操作系统 冲浪宝典
软件教学 认证考试

网络安全 网络办公 行业资讯 评测对比
您当前位置:站长天空 -> 图形图象-> Authorware教程
C#中调用Windows API的要点-.NET教程,C#语言
作者:网友供稿 点击:10
推荐
西部数码-全国虚拟主机10强!20余项虚拟主机管理功能,全国领先!第6代双线路虚拟主机,南北访问畅通无阻!可在线rar解压,自动数据恢复设置虚拟目录等.免费赠送访问统计,企业邮局.Cn域名注册10元/年,自助建站480元起,免费试用7天,满意再付款!P4主机租用799元/月.月付免压金
站内搜索
文章页数:[1] 
  在.net framework sdk文档中,关于调用windows api的指示比较零散,并且其中稍全面一点的是针对visual basic .net讲述的。本文将c#中调用api的要点汇集如下,希望给未在c#中使用过api的朋友一点帮助。另外如果安装了visual studio .net的话,在c:\program files\microsoft visual studio .net\frameworksdk\samples\technologies\interop\platforminvoke\winapis\cs目录下有大量的调用api的例子。

  一、调用格式

using system.runtime.interopservices; //引用此名称空间,简化后面的代码
...
//使用dllimportattribute特性来引入api函数,注意声明的是空方法,即方法体为空。
[dllimport("user32.dll")]
public static extern returntype functionname(type arg1,type arg2,...);
//调用时与调用其他方法并无区别

  可以使用字段进一步说明特性,用逗号隔开,如:

[ dllimport( "kernel32", entrypoint="getversionex" )]
dllimportattribute特性的公共字段如下:

  1、callingconvention 指示向非托管实现传递方法参数时所用的 callingconvention 值。

  callingconvention.cdecl : 调用方清理堆栈。它使您能够调用具有 varargs 的函数。
  callingconvention.stdcall : 被调用方清理堆栈。它是从托管代码调用非托管函数的默认约定。

  2、charset 控制调用函数的名称版本及指示如何向方法封送 string 参数。

  此字段被设置为 charset 值之一。如果 charset 字段设置为 unicode,则所有字符串参数在传递到非托管实现之前都转换成 unicode 字符。这还导致向 dll entrypoint 的名称中追加字母“w”。如果此字段设置为 ansi,则字符串将转换成 ansi 字符串,同时向 dll entrypoint 的名称中追加字母“a”。大多数 win32 api 使用这种追加“w”或“a”的约定。如果 charset 设置为 auto,则这种转换就是与平台有关的(在 windows nt 上为 unicode,在 windows 98 上为 ansi)。charset 的默认值为 ansi。charset 字段也用于确定将从指定的 dll 导入哪个版本的函数。charset.ansi 和 charset.unicode 的名称匹配规则大不相同。

  对于 ansi 来说,如果将 entrypoint 设置为“mymethod”且它存在的话,则返回“mymethod”。如果 dll 中没有“mymethod”,但存在“mymethoda”,则返回“mymethoda”。对于 unicode 来说则正好相反。如果将 entrypoint 设置为“mymethod”且它存在的话,则返回“mymethodw”。如果 dll 中不存在“mymethodw”,但存在“mymethod”,则返回“mymethod”。如果使用的是 auto,则匹配规则与平台有关(在 windows nt 上为 unicode,在 windows 98 上为 ansi)。如果 exactspelling 设置为 true,则只有当 dll 中存在“mymethod”时才返回“mymethod”。

  3、entrypoint 指示要调用的 dll 入口点的名称或序号。

  如果你的方法名不想与api函数同名的话,一定要指定此参数,例如:


[dllimport("user32.dll",charset="charset.auto",entrypoint="messagebox")]
public static extern int msgbox(intptr hwnd,string txt,string caption, int type);

  4、exactspelling 指示是否应修改非托管 dll 中的入口点的名称,以与 charset 字段中指定的 charset 值相对应。如果为 true,则当 dllimportattribute.charset 字段设置为 charset 的 ansi 值时,向方法名称中追加字母 a,当 dllimportattribute.charset 字段设置为 charset 的 unicode 值时,向方法的名称中追加字母 w。此字段的默认值是 false。

  5、preservesig 指示托管方法签名不应转换成返回 hresult、并且可能有一个对应于返回值的附加 [out, retval] 参数的非托管签名。

  6、setlasterror 指示被调用方在从属性化方法返回之前将调用 win32 api setlasterror。 true 指示调用方将调用 setlasterror,默认为 false。运行时封送拆收器将调用 getlasterror 并缓存返回的值,以防其被其他 api 调用重写。用户可通过调用 getlastwin32error 来检索错误代码。



二、参数类型:

  1、数值型直接用对应的就可。(dword -> int , word -> int16)

  2、api中字符串指针类型 -> .net中string

  3、api中句柄 (dword) -> .net中intptr

  4、api中结构 -> .net中结构或者类。注意这种情况下,要先用structlayout特性限定声明结构或类

  公共语言运行库利用structlayoutattribute控制类或结构的数据字段在托管内存中的物理布局,即类或结构需要按某种方式排列。如果要将类传递给需要指定布局的非托管代码,则显式控制类布局是重要的。它的构造函数中用layoutkind值初始化 structlayoutattribute 类的新实例。 layoutkind.sequential 用于强制将成员按其出现的顺序进行顺序布局。

  layoutkind.explicit 用于控制每个数据成员的精确位置。利用 explicit, 每个成员必须使用 fieldoffsetattribute 指示此字段在类型中的位置。如:


[structlayout(layoutkind.explicit, size=16, charset=charset.ansi)]
public class mysystemtime
{
[fieldoffset(0)]public ushort wyear;
[fieldoffset(2)]public ushort wmonth;
[fieldoffset(4)]public ushort wdayofweek;
[fieldoffset(6)]public ushort wday;
[fieldoffset(8)]public ushort whour;
[fieldoffset(10)]public ushort wminute;
[fieldoffset(12)]public ushort wsecond;
[fieldoffset(14)]public ushort wmilliseconds;
}

  下面是针对api中osversioninfo结构,在.net中定义对应类或结构的例子:


/**********************************************
* api中定义原结构声明
* osversioninfoa struct
* dwosversioninfosize dword ?
* dwmajorversion dword ?
* dwminorversion dword ?
* dwbuildnumber dword ?
* dwplatformid dword ?
* szcsdversion byte 128 dup (?)
* osversioninfoa ends
*
* osversioninfo equ <osversioninfoa>
*********************************************/

//.net中声明为类
[ structlayout( layoutkind.sequential )]
public class osversioninfo
{
public int osversioninfosize;
public int majorversion;
public int minorversion;
public int buildnumber;
public int platformid;

[ marshalas( unmanagedtype.byvaltstr, sizeconst=128 )]
public string versionstring;
}
//或者
//.net中声明为结构
[ structlayout( layoutkind.sequential )]
public struct osversioninfo2
{
public int osversioninfosize;
public int majorversion;
public int minorversion;
public int buildnumber;
public int platformid;

[ marshalas( unmanagedtype.byvaltstr, sizeconst=128 )]
public string versionstring;
}


  此例中用到mashalas特性,它用于描述字段、方法或参数的封送处理格式。用它作为参数前缀并指定目标需要的数据类型。例如,以下代码将两个参数作为数据类型长指针封送给 windows api 函数的字符串 (lpstr):


[marshalas(unmanagedtype.lpstr)]
string existingfile;
[marshalas(unmanagedtype.lpstr)]
string newfile;

  注意结构作为参数时候,一般前面要加上ref修饰符,否则会出现错误:对象的引用没有指定对象的实例。


[ dllimport( "kernel32", entrypoint="getversionex" )]
public static extern bool getversionex2( ref osversioninfo2 osvi );

  三、如何保证使用托管对象的平台调用成功?

  如果在调用平台 invoke 后的任何位置都未引用托管对象,则垃圾回收器可能将完成该托管对象。这将释放资源并使句柄无效,从而导致平台invoke 调用失败。用 handleref 包装句柄可保证在平台 invoke 调用完成前,不对托管对象进行垃圾回收。

  例如下面:


filestream fs = new filestream( "a.txt", filemode.open );
stringbuilder buffer = new stringbuilder( 5 );
int read = 0;
readfile(fs.handle, buffer, 5, out read, 0 ); //调用win api中的readfile函数

  由于fs是托管对象,所以有可能在平台调用还未完成时候被垃圾回收站回收。将文件流的句柄用handleref包装后,就能避免被垃圾站回收:


[ dllimport( "kernel32.dll" )]
public static extern bool readfile(
handleref hndref,
stringbuilder buffer,
int numberofbytestoread,
out int numberofbytesread,
ref overlapped flag );
......
......
filestream fs = new filestream( "handleref.txt", filemode.open );
handleref hr = new handleref( fs, fs.handle );
stringbuilder buffer = new stringbuilder( 5 );
int read = 0;
// platform invoke will hold reference to handleref until call ends
readfile( hr, buffer, 5, out read, 0 );



文章整理:站长天空 网址:http://www.z6688.com/
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

文章页数:[1] 


放大字体显示 缩小字体显示 打印文章 推荐给朋友
热门文章
·Java面试中的陷阱-JSP教程,Java技巧及代码
·通过JavaMail访问Hotmail邮箱-JSP教程,Java技巧及代码
·ASP.NET中使用自定义验证控件-.NET教程,Asp.Net开发
·燃气轮机发电机组的开发与应用——张树治
·有数据绑定、排序、查找功能的ListView(二):-.NET教程,数据库应用
·显示日期格式的几个函数-ASP教程,ASP应用
·在.NET下获取硬盘序列号的问题-.NET教程,.NET Framework
·use MSAgent in C#-.NET教程,C#语言
·利用光缆传输有线电视信号
·电信级宽带应用网站并发性承载均衡研究
最新文章
·photoshop照片处理:色彩的强化及优化_photoshop教程
·献给想我一样初基础网站优化的朋友们_seo网站优化
·百度联盟认证计划 与合作伙伴互惠共赢_网赚技巧
·如何去选择广告联盟和联盟广告_网赚技巧
·专业的网站流量快速提升的方法_站长心得
·改进网络营销的10种方法_站长心得
·教你最大限度地提高 google adsense 收入的技巧_google推广
·如何建立网站地图(site map)_站长心得
·seo偏门绝技之关键词隐身大法_seo网站优化
·265步hao123后尘被清空数据,谁来代替alexa排名?_alexa排名
相关主题
  • c#中调用windows api的要点_c#应用
  • C#中调用Windows API的要点-.NET教程,C#语言
  • c#中调用mapx5.0(一)-.NET教程,C#语言
  • C#中调用Windows API的要点-.NET教程,C#语言
  • C#中调用消息对话框,并取得其返回值-.NET教程,C#语言
  • 西部数码虚拟主机

    友情链接
    CNNIC 西部数码
    万网 自助建站
    虚拟主机 asp空间
    域名注册 域名
    域名申请 主页空间
    论坛空间 网站空间
    国际域名 虚拟空间
    空间租用 DDOS防火墙
    成都主机托管 四川主机托管
    主机租用 服务器租用
    网站目录 自助建站
    虚拟主机 网址大全
    软件下载
    自助链接
    虚拟主机资讯 特价虚拟主机
    版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
    关于我们:站长天空:专业提供最新的站长资讯、在线教程、虚拟主机权威评测、虚拟主机性能对比、网站制作教程,开发教程,站长工具。包括网页制作教程、冲浪宝典、编程参考、操作系统、软件教学、行业动态等。
    特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。
    发表评论 打印  刷新     关闭