2013-05-20 26 views
2

這是從的libeay32.dll(openssl project)功能:ç無符號`字符** out`到C#`的byte []`

int i2o_ECPublicKey (EC_KEY * key, unsigned char ** out) 

如何描述它在C#中(如果我想獲得一個字節[])?

代碼:

[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] 
public extern static int i2o_ECPublicKey (IntPtr encKey, StringBuilder outPar); 

我不喜歡這一點,因爲我覺得這個結果是unicode。

回答

 [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] 
     public extern static int i2o_ECPublicKey(IntPtr encKey, ref IntPtr outPar); 

     [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] 
     public static extern int i2o_ECPublicKey(IntPtr encKey, int outPar); 


     //Pass *out as null for required buffer length. 
     int reqLen = i2o_ECPublicKey(k, 0); 

     Byte[] outBuf = new Byte[reqLen]; 
     IntPtr unmanagedOut = Marshal.AllocCoTaskMem(outBuf.Length); 
     int res = i2o_ECPublicKey(k, ref unmanagedOut); 
     if (res == reqLen) 
     { 
      unmanagedOut -= reqLen; // because i2o_ECPublicKey add size to unmanagedOut 
      Marshal.Copy(unmanagedOut, outBuf, 0, outBuf.Length); 
     } 
     Marshal.FreeCoTaskMem(unmanagedOut); 

回答

2

我相信做手工,你需要使用Marshal.Copy從非託管內存數組複製到管理的byte []。 (請注意,代碼未經測試)。

public extern static int i2o_ECPublicKey (IntPtr encKey, ref IntPtr outPar); 

... 
//Pass *out as null for required buffer length. 
int reqLen = i2o_ECPublicKey(key, null); 

Byte[] outBuf = new Byte[reqLen]; 
IntPtr unmanagedOut = Marshal.AllocCoTaskMem(outBuf.Length); 
int res = i2o_ECPublicKey(key, ref unmanagedOut); 
if (res == 1) { 
    Marshal.Copy(unmanaged, outBuf, 0, outBuf.Length); 
} 
Marshal.FeeCoTaskMem(unmanagedOut); 
0

您可以通過使用GetBytes

StringBuilder outPar; 
string result = ""; 
byte[] parbytes = System.Text.Encoding.Unicode.GetBytes(outPar.ToString()); 
foreach(byte parbyte in parbytes) 
{ 
    result+= Convert.ToChar(parbyte); 
} 
return result; 
獲得與正確的編碼字符串