4

我有以下几行代码:

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();
}

解密方法的减速是:

internal static class UnsafeNativeMethods
{
  [DllImport(_dllLocation, CallingConvention = CallingConvention.Cdecl)]
  public static extern IntPtr Decrypt(string track1, int dataLen);
 }

unsigned char*visual c++代码中返回,每当我从代码中调用 dll 时,c#它总是返回“ System.Byte[]”而不是值。我在这里做错了marshal吗?

请在这里帮助我

4

2 回答 2

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();
}
于 2012-12-27T10:51:41.567 回答
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 (=Default)

于 2012-12-27T10:51:56.860 回答