如何从c#中获取Marshal的值

我有以下几行代码:

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

我从visual c代码返回unsigned char *,每当我从c#代码调用dll时,它总是返回“System.Byte []”而不是value.我在元帅身上做错了吗?

请帮帮我

最佳答案 你错过了从byte []到string的转换,但是你必须定义什么是编码.这可能有效:

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)

点赞