问题遇到的现象和发生背景 :1、char* 类型转化为byte[] C# 乱码 2、使用结构体传入传出哪里错了
问题相关代码,请勿粘贴截图
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Input
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8192)]
public string Name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8192)]
public string Value;
};
public struct Output
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string Name;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
public string Value;
};
调用接口void TestLog(char* Log)
参数Log返回当前的测试信息,注意该参数需提前分配内存,建议分配内存大于1M;函数返回值为void。
byte[] sb = new byte[8912];
String SBBB = "";
StringBuilder sr = new StringBuilder(8192);
// log =IntPtr.Zero;
CatchTestLog(sr); -----------使用stringBuilder 无数据 使用 byte[]获取到是乱码
Marshal.Copy(log, sb, 0, 8912);
richTextBox1.AppendText("LOG:" + sr.ToString());
调用接口 int Test (constInput *inputP, const int Length, Output *Outp, int &OutputLength)
改成c# [DllImport("UNIT_PLATFORM_MANAGE.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public extern static int TestExecute(IntPtr paraInput, int paraLength, IntPtr paraOutput, ref int Leghth_Data);
int count = Marshal.SizeOf(typeof(Input));
IntPtr pv = Marshal.AllocHGlobal(count * 4);
int STRLOG = 0;
Input par1 = new Input();
par1.Name = CODE";
par1.Value = @"222";
Marshal.StructureToPtr(par1, pv, true);
Input par2 = new Input();
par2.Name = "卡号";
par2.Value = @"11111";
Marshal.StructureToPtr(par2, (IntPtr)(pv.ToInt64() + count), true);
Input par3 = new Input();
par3.Name = "姓名";
par3.Value = @"2222";
Marshal.StructureToPtr(par3, (IntPtr)(pv.ToInt64() + count*2), true);
Input par4 = new Input();
par4.Name = "性别";
par4.Value = @"男";
Marshal.StructureToPtr(par3, (IntPtr)(pv.ToInt64() + count * 3), true);
IntPtr log = Marshal.AllocHGlobal(8192);
//传出
int countOutp = Marshal.SizeOf(typeof(Output));
IntPtr pvOut = Marshal.AllocHGlobal(countOutp * 4);
//IntPtr paraOnput1 = Marshal.AllocHGlobal(countOutp * 1);
Output parOup1 = new Output();
byte[] xx=new byte[10];
ParameterOutput[] PP=new ParameterOutput[10];
int leg = 0;
if (TestExecute(pv, 4, pvOut,ref leg) == 1)
{
MessageBox.Show("测试成功");
}
else
{
MessageBox.Show("测试失败");
}
运行结果及报错内容 1、 char* 类型转化为byte[] C# 乱码 2、使用结构体传入传出定义那里错了
我的解答思路和尝试过的方法
我想要达到的结果
这里有比较具体的解决方案。