C# DLLImport的理解

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

先不考虑概念,简单的说就是调用dll中的某个方法。以例子说明。

创建一个form,在其上添加按钮。按钮的点击事件为button1_Click(object sender, EventArgs e)。

    //struct 收集系统情况

    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEM_INFO
    {
        public uint dwOemId;
        public uint dwPageSize;
        public uint lpMinimumApplicationAddress;
        public uint lpMaximumApplicationAddress;
        public uint dwActiveProcessorMask;
        public uint dwNumberOfProcessors;
        public uint dwProcessorType;
        public uint dwAllocationGranularity;
        public uint dwProcessorLevel;
        public uint dwProcessorRevision;
    }

public partial class Form1 : Form

{

        public Form1()
        {
            InitializeComponent();
        }

        //获取系统信息
        [DllImport("kernel32")]
        static extern void GetSystemInfo(ref SYSTEM_INFO pSI);

        private void button1_Click(object sender, EventArgs e)
        {
            SYSTEM_INFO pSI = new SYSTEM_INFO();
            GetSystemInfo(ref pSI);
        }

}

说明:

1.点击按钮的时候会发现pSI的值已经发生了变化,里面包含系统信息。

2.SYSTEM_INFO为自定义的结构体,但结构体的参数个数和参数类型要与GetSystemInfo()方法的一致。

3.DllImport的方法的必须写成static extern ,可以修饰为public等。

-------------------------------------------------------------------------------------------
        根据上面的调用方式,我们可以同样方式调用自定义的dll吗?
        首先创建一个工程Import,并有Class1
        namespace Import
        {
            public class Class1
            {
                public static string ImportMeth(string str)
                {
                    return "you are success!";
                }
            }
        }
        然后以同样方式调用,
        //自定义的dll
        [DllImport("Import")]
        public static extern string ImportMeth(string a);
        在button1_Click(object sender, EventArgs e)里追加以下代码:
        string strRet = ImportMeth("123");
        运行后发现报错"Unable to find an entry point named 'ImportMeth' in DLL 'Import'.":"",
        试着把dll引入到工程的参照中,一样报错。
        最终查出来,原来DLLImport 用于托管程序调符合DLL规范的非托管程序动态类库.如果是调用托管程序类库,直接引用就行了。
        所以我们不需要也不能DLLImport,而应该添加using Import;
        string strRet = Class1.ImportMeth("123");
        这样就可以得到结果“you are success!”了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值