2012-12-27 40 views
4

我的代碼下面幾行:如何從元帥獲得在C#中的價值

public static string getTrack1(string track1, int len) 
{ 
    IntPtr track1Ptr = UnsafeNativeMethods.Decrypt(track1, len); 
    Byte[] track1b = new Byte[200]; 
    Marshal.Copy(track1Ptr, track1b, 0, track1b.Length); 
    return track1b.ToString(); 
} 

解密方法的減速是:

我從visual c++代碼,每當返回unsigned char*我我打電話給dll從c#代碼它總是返回「System.Byte[]」而不是價值。我在marshal這裏做錯了嗎?

請幫我在這裏

回答

1

你錯過了從字符串的byte []的轉變,但你必須定義什麼是編碼。這可能有效:

public static string getTrack1(string track1, int len) 
{ 
    IntPtr track1Ptr = UnsafeNativeMethods.Decrypt(track1, len); 
    Byte[] track1b = new Byte[200]; 
    Marshal.Copy(track1Ptr, track1b, 0, track1b.Length); 
    return Encoding.Default.GetString(track1b); 
} 

但是這樣做會更好;

public static string getTrack1(string track1, int len) 
{ 
    IntPtr track1Ptr = UnsafeNativeMethods.Decrypt(track1, len); 
    return Marshal.PtrToStringAnsi(track1Ptr); 
} 

如果編碼是ANSI(=默認)

1

Byte[].ToString()方法總是返回System.Byte[]

爲字節數組轉換成字符串表示你必須做這樣的事情:

public static string ByteArrayToHexString(byte[] source) 
{ 
    StringBuilder builder = new StringBuilder(source.Length * 3); 

    foreach (byte b in source) 
    { 
     builder.Append(b.ToString("X2")); 
     builder.Append(' '); 
    } 

    return builder.ToString(); 
}