当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用DllImport调用非托管的代码的方法

C#使用DllImport调用非托管的代码的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

找到getshortpathname的方法签名,

dword getshortpathname(lpctstr tpszlongpath,tptstr lpszshortpath,dword cchbuffer);

非托管及托管数据类型对应关系:

lpctstr         string

lptstr           stringbuilder

dword          int

dllimport的导入规则:

1、方法名与win api完全一样。如果在c#中调用时显示完全不同的方法名称,则需要引入entrypoint属性,使用别名显示。

2、函数除需要dllimport类修饰符外,还需要声明public static extern类型。

3、函数返回值和参数必须和调用的api的完全一样。

4、必须引入system.runtime.interopservices命名空间。

代码:

复制代码 代码如下:

using system.runtime.interopservices;

public class test

        {

            [dllimport("kernel32.dll",charset=charset.auto,entrypoint="getshort")]

public static extern int getshortpathname(

                [marshalas(unmanagedtype.lptstr)] string path,

                [marshalas(unmanagedtype.lptstr)] stringbuilder shortpath,

int shortpathlength);

        }


代码调用中kernel32.dll的路径之所以没写是因为dllimport会按照以下三种顺序查找dll:

1、exe所在目录;2、system32目录;3、环境变量目录。

marshalas为可选类型,因为每个数据类型都有默认的封送行为,该属性指示如何在托管代码和非托管代码之间的封送数据,可将该属性用于参数、字段和返回值。大多数情况下该属性只是用unmanagedtype枚举类型就能满足大多数非托管的数据类型,如默认情况下字符会被当作bstr传入到dll中,可以使用marshalas将字符串指定为lptstr、lpwstr或lpstr等。

dllimport可选属性解释

entrypoint             可对方法采用不同的名称,使用别名

charset                  函数调用使用unicode还是ansi

exactspelling        false,表示让编译器自己选择使用unicode或ansi

callingconvetnion             它的参数指示入口点调用的约定;不指定默认为callingconvention.winapi

preservesig                    指示方法签名应当被保留还是被转换,当被转换时它被转换为一个具有hresult返回值和该返回值的一个名为retval的附加输出参数的签名,默认为true。

setlasterror                   指定是否保留上一次错误,默认为false

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网