c#进程之间对象传递方法

2019-12-30 17:06:29王冬梅

1. 起源

KV项目下载底层重构升级决定采用独立进程进行Media下载处理,以能做到模块复用之目的,因此涉及到了独立进程间的数据传递问题。

目前进程间数据传递,多用WM_COPYDATA、共享dll、内存映射、Remoting等方式。相对来说,WM_COPYDATA方式更为简便,网上更到处是其使用方法。

而且Marshal这个静态类,其内置多种方法,可以很方便实现字符串、结构体等数据在不同进程间传递。

那么,对象呢?如何传递?

2、序列化

想到了,Newtonsoft.Json.dll这个神器。相对于内建的XmlSerializer这个东西,我更喜欢用Json。

那么,如此处理吧,我们来建个Demo解决方案,里面有HostApp、ClildApp两个项目,以做数据传递。

3、ChildApp项目

先说这个,我没有抽取共用的数据单独出来,而做为Demo,直接写入此项目中,HostApp引用此项目,就可引用其中public出来的数据类型。

数据结构部分代码:


[StructLayout(LayoutKind.Sequential)]
 public struct COPYDATASTRUCT
 {
  public IntPtr dwData;
  public int cbData;
  [MarshalAs(UnmanagedType.LPStr)]
  public string lpData;
 }
 [Serializable]
 public class Person
 {
  private string name;
  private int age;
  private List<Person> children;
  public Person(string name, int age)
  {
   this.name = name;
   this.age = age;
   this.children = new List<Person>();
  }
  public string Name
  {
   get { return this.name; }
   set { this.name = value; }
  }
  public int Age
  {
   get { return this.age; }
   set { this.age = value; }
  }
  public List<Person> Children
  {
   get { return this.children; }
  }
  public void AddChildren()
  {
   this.children.Add(new Person("liuxm", 9));
   this.children.Add(new Person("liuhm", 7));
  }
  public override string ToString()
  {
   string info = string.Format("姓名:{0},年龄:{1}", this.name, this.age);
   if (this.children.Count != 0)
   {
    info += (this.children.Count == 1) ? "rn孩子:" : "rn孩子们:";
    foreach (var child in this.children)
     info += "rn" + child.ToString();
   }
   return info;
  }
 }

窗体代码:


public partial class ChildForm : Form
 {
  public const int WM_COPYDATA = 0x004A;
  private IntPtr hostHandle = IntPtr.Zero;
  Person person = new Person("liujw", 1999);
  [DllImport("User32.dll", EntryPoint = "SendMessage")]
  private static extern int SendMessage(
   IntPtr hWnd,    // handle to destination window
   int Msg,     // message
   int wParam,    // first message parameter
   ref COPYDATASTRUCT lParam // second message parameter
  );
  public ChildForm(string[] args)
  {
   InitializeComponent();
   if (args.Length != 0)
    this.hostHandle = (IntPtr)int.Parse(args[0]);
  }
  private void btnSubmit_Click(object sender, EventArgs e)
  {
   this.person.Name = txtName.Text;
   int age;
   this.person.Age = int.TryParse(txtAge.Text, out age) ? age : 0;
   this.person.AddChildren();
   if (this.hostHandle != IntPtr.Zero)
   {
    string data = GetPersionStr();
    COPYDATASTRUCT cds = new COPYDATASTRUCT();
    cds.dwData = (IntPtr)901;
    cds.cbData = data.Length + 1;
    cds.lpData = data;
    SendMessage(this.hostHandle, WM_COPYDATA, 0, ref cds);
   }
  }
  private string GetPersionStr()
  {
   return JsonConvert.SerializeObject(this.person);
  }
 }