C#想要调用Dephi接口方法,有两种解决办法

一、将Dephi程序编译成一个COM组件,然后在C#里引用COM组件,

二、非托管调用Dephi的DLL文件,代码如下:

Dephi接口方法:

function RSADecrypt(aPKey, aDKey, aData : PChar; aBuffer : pointer; aBufferSize: DWORD): integer; stdcall;

function RSAEncrypt(aPKey, aData : PChar; aBuffer : pointer; aBufferSize: DWORD): integer; stdcall;

function AESDecrypt(aData : PChar; aBuffer : pointer; aBufferSize: DWORD): integer;

 

 

 

 DrawChartFromDll
    {
        //调用非托管Dll,

        [DllImport(
"rsaadpter.dll", EntryPoint = "RSAEncrypt", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        
        
/// RSA加密
        public static extern int RSAEncrypt(string aPKey, string aData,IntPtr aBuffer, int aBufferSize);



        [DllImport(
"rsaadpter.dll", EntryPoint = "RSADecrypt", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        
        
/// RSA解密
        public static extern int RSADecrypt(string aPKey, string aDKey, string aData,IntPtr aBuffer, int aBufferSize);



        [DllImport(
"rsaadpter.dll", EntryPoint = "AESDecrypt", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        
        
/// 普通AES解密
        public static extern int AESDecrypt(string aData,IntPtr aBuffer, int aBufferSize);
    } 

 

 


IntPtr ptr = Marshal.AllocHGlobal(2000);                //非托管定义指针,指定长度2000
int resu = DrawChartFromDll.RSADecrypt(publicKey, privateKey, data, ptr, 2000);  //Dephi接口方法,RSA解密私钥
data = ToStringFromIntPtr(ptr, resu);                   //获取RSA解密后字符串


/// <summary>
/// 从IntPtr指针,获取字符串
/// </summary>
/// <param name="ptr">指针</param>
/// <param name="result">获取字符串字节数</param>
/// <returns></returns>
private string ToStringFromIntPtr(IntPtr ptr,int result)
{
    
if (result <= 0)
    {
        Marshal.FreeHGlobal(ptr);       
//Marshal释放指针分配的内存
        return "0";
    }

    
byte[] b = new byte[result];        
    Marshal.Copy(ptr, b, 
0, result);    //
    Marshal.FreeHGlobal(ptr);           //Marshal释放指针分配的内存

    
return System.Text.Encoding.Default.GetString(b, 0, result);   //获取解密后的私钥字符串
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
  • 2021-09-27
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
猜你喜欢
  • 2021-12-18
  • 2022-12-23
  • 2022-01-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-11
相关资源
相似解决方案