c# 引用外部dll

 1,实现类
   public class SecurityA
    {
        //extern修饰符支持在外部实现方法
        //外部修饰符的常见方法是在使用Interop 服务调入非托管代码时与 DllImport 属性一起使用;
        //方法还必须声明为 static
        [DllImport("securityA.dll")]
        static extern IntPtr DeCode(IntPtr source, IntPtr key);
        [DllImport("securityA.dll")]
        static extern IntPtr EnCode(IntPtr source, IntPtr key);

        public string enCrypt(string source,string key) 
        {
            string output = string.Empty;
            try 
            {
                //转换为基本类型 IntPtr: 用于表示指针或句柄的平台特定类型。
                IntPtr ptrIn = Marshal.StringToHGlobalAnsi(source);
                IntPtr ptrInKey = Marshal.StringToHGlobalAnsi(key);
                IntPtr ptrRtn = EnCode(ptrIn, ptrInKey);
                output = Marshal.PtrToStringAnsi(ptrRtn);
            }
            catch(Exception e) 
            {
                throw e;
            }
            return output;
        }

        public string deCrypt(string source, string key)
        {
            string strRtn = string.Empty;
            try 
            {
                IntPtr ptrIn = Marshal.StringToHGlobalAnsi(source);
                IntPtr ptrInKey = Marshal.StringToHGlobalAnsi(key);
                IntPtr ptrRtn = DeCode(ptrIn, ptrInKey);
                strRtn = Marshal.PtrToStringAnsi(ptrRtn);
            }
            catch(Exception e)
            {
                throw e;
            }

            return strRtn;
        }
    }

2,调用

  string strKey =  string.Empty ;
            SecurityA sa = new SecurityA();

            btnEncode.Click += delegate 
            {
                //加密
                string strCode = sa.enCrypt(txtBefore.EditValue.ToString(),strKey);
                txtAfter.Text = strCode;
            };

            btnDecode.Click += delegate 
            {
                //解密
                string strCode = sa.deCrypt(txtAfter.EditValue.ToString(), strKey);
                txtDecode.Text = strCode;
            };

            txtKey.EditValueChanged += delegate {   strKey = txtKey.EditValue == null ? string.Empty : txtKey.EditValue.ToString(); };



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值