zoukankan      html  css  js  c++  java
  • c# 引用外部dll

    c# 引用外部dll

    2015-12-09 20:39:38 aaa_dai 阅读数 604 文章标签: DllImportsecurityA.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,调用 

    
     
    1. string strKey = string.Empty ;

    2. SecurityA sa = new SecurityA();

    3.  
    4. btnEncode.Click += delegate

    5. {

    6. //加密

    7. string strCode = sa.enCrypt(txtBefore.EditValue.ToString(),strKey);

    8. txtAfter.Text = strCode;

    9. };

    10.  
    11. btnDecode.Click += delegate

    12. {

    13. //解密

    14. string strCode = sa.deCrypt(txtAfter.EditValue.ToString(), strKey);

    15. txtDecode.Text = strCode;

    16. };

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

  • 相关阅读:
    数理统计与Matlab: 第4章 回归分析
    汽车各部位名称详解【图】
    线性代数:第四章 矩 阵1
    曲线救国的就业路线是否合理?
    TortoiseSVN 编辑日志信息报错
    Ironpython及其他托管语言中值类型最好使用构造函数赋值,否则无法赋值的问题
    线性代数:第五章 二次型
    Matlab基础
    技术基层管理者交流QQ群243460070
    MATLAB软件基础
  • 原文地址:https://www.cnblogs.com/grj001/p/12223490.html
Copyright © 2011-2022 走看看