Hello, the recent use of unity to do the process of communication, should be and C + + PC-side to achieve communication, only started confused, and then realized that it is very complicated ... First of all, I would appreciate the help of Baidu, Google and the game circle of the big players.
There are many ways to communicate in a process, but wm_copydate is definitely much better than other memory shares.
Most of unity is in the C # language, and C # itself Forms This DLL also provides the reception of Windows messages but not very good use of System.Windows.Forms in unity, so in the following my Code I use Unity to send a process message is User32.dll in the SendMessage. The hook to be used for the reception.
The following code is the communication of the EXE packaged by unity. will not communicate with C + +. The principle is the same.
The whole process to import user32.dll, so in need of using System.Runtime.InteropServices, the remaining need to refer to what to add, there are also send JSON data and a lot of details of the C # fetch address read address, I also share everyone's fun , I will help you later.
Send side (using SendMessage), Test1.cs mounted in unity scene
Using system;using unityengine;using system.collections;using system.runtime.interopservices;using System.Text; public class test15:monobehaviour{#region public IntPtr m_hwnd; <summary>////Send Windows messages convenient for SendMessage functions in user32.dll Use//</summary> public struct COPYDATASTRUC T {public IntPtr dwdata; public int cbdata; Public INTPTR lpdata; }//user32.dll in SendMessage [DllImport ("User32.dll")] public static extern IntPtr SendMessage (IntPtr hWnd, uint M SG, int wParam, ref copydatastruct LParam); Get window handle in User32.dll [DllImport ("User32.dll")] public static extern IntPtr FindWindow (string strclassname, String St Rwindowname); Macro Definition Private Const ushort Ipc_ver = 1; Private Const int idt_asynchronism = 0x0201; Private Const UINT WM_COPYDATA = 0x004a; Private Const USHORT Ipc_cmd_gf_socket = 1; Private Const USHORT Ipc_sub_gf_socket_send = 1; Private Const int ipc_sub_gf_client_ready = 1; Private Const int Ipc_cmd_gf_control = 2; Private Const int ipc_buffer = 10240;//Max buffer length//lookup window private IntPtr Hwndpalaz; The data header is used with public unsafe struct Ipc_head {public ushort wversion; public ushort Wpacketsize; public ushort Wmaincmdid; public ushort Wsubcmdid; } public unsafe struct Ipc_buffer {public ipc_head Head; Ipc_head structure Public fixed byte cbbuffer[ipc_buffer]; The pointer holds the JSON data using byte[] to receive the store} #endregion//<summary>///Send JSON to Pointer to SendData () method///</SU mmary> private void Sendjson () {IntPtr Hwndpalaz = FindWindow (null, "The name of the window you are looking for");//is the title of the window Debug.lo g (Hwndpalaz); if (Hwndpalaz! = null) {//Get the game itself handle m_hwnd = FindWindow ("Unitywndclass", null); Send the user to prepare the message (this is a JSON plugin I will not provide your own JSON new instance of the example here does not change the error) Jsonobject Jsstart = new Jsonobject (); Jsstart.addfield ("66", "It's Me"); Jsstart.addfield ("Sya", "Learning game in order to install Force Group"); Jsstart.addfield ("Doing", "This Is your Time"); String urstr = Jsstart.tostring (); byte[] bytes = Encoding.UTF8.GetBytes (URSTR); IntPtr pData = marshal.allochglobal (2 * bytes. Length); Marshal.Copy (bytes, 0, PData, bytes. Length); SendData (M_hwnd, Ipc_cmd_gf_socket, Ipc_sub_gf_socket_send, PData, (ushort) bytes. Length); }}///<summary>//SendMessage Send///</summary>/<param name= "Hwndserver" > Pointer < ;/param>//<param name= "Wmaincmdid" > Main command </param>//<param name= "wsubcmdid" > Secondary command </param> <param name= "PData" >json conversion pointers </param>///<param Name= "wdatasize" > Data size </param>/// lt;returns></returns> Public unsafe bool SendData (IntPtr hwndserver, ushort Wmaincmdid, ushort Wsubcmdid, INTP TR PData, ushort wdatasize) {//Assign value to Ipcbuffer structure Ipc_buffer Ipcbuffer; IPCBuffer.Head.wVersion = Ipc_ver; IPCBuffer.Head.wSubCmdID = Wsubcmdid; IPCBuffer.Head.wMainCmdID = Wmaincmdid; IPCBuffer.Head.wPacketSize = (ushort) marshal.sizeof (typeof (Ipc_head)); Memory operation if (pData! = null) {//Checksum length if (Wdatasize > 1024x768) return false; Copy data IPCBuffer.Head.wPacketSize + = Wdatasize; byte[] bytes = new Byte[ipc_buffer]; Marshal.Copy (pData, Bytes, 0, wdatasize); for (int i = 0; i < Ipc_buffer; i++) {ipcbuffer.cbbuffer[i] = bytes[i]; }}//Send data copydatastruct copydatastruct; ipc_buffer* Ppcbuffer = &IPCBuffer; Copydatastruct.lpdata = (IntPtr) ppcbuffer; Copydatastruct.dwdata = (IntPtr) idt_asynchronism; Copydatastruct.cbdata = IPCBuffer.Head.wPacketSize; SendMessage (Hwndserver, 0x004a, (int) m_hwnd, ref copydatastruct); return true; } void Update () {Sendjson ();//Always Send convenient test}}
The receiving end Test2.cs a random scene to save the script to mount the scene on top of the object. Then use Unity to package the PC-side EXE to receive the use of Windows Hook hooks (here I do not do a specific stare, I feel the magic of the hook, I do not know can give me a message)
Using unityengine;using system;using system.diagnostics;using system.runtime.interopservices;using Debug = Unityengine.debug;public class test2:monobehaviour{//Hook receives the structure of the message public struct cwpstruct{public int lparam; public int wparam; public UINT Message; Public INTPTR hwnd;} Build hooks [DllImport ("user32.dll", CharSet = CharSet.Auto, callingconvention = callingconvention.stdcall)] Private stat IC extern int SetWindowsHookEx (int idhook, HookProc lpfn, IntPtr hinstance, uint dwthreadid); Remove hooks [DllImport ("user32.dll", CharSet = CharSet.Auto, callingconvention = callingconvention.stdcall)] Private stat IC extern bool UnhookWindowsHookEx (int idhook); Pass the message to the next listener [DllImport ("user32.dll", CharSet = CharSet.Auto, callingconvention = callingconvention.stdcall)] Priva Te static extern int CallNextHookEx (int idhook, int nCode, int wParam, int lParam);//callback entrusted private delegate int HookProc (int nCode, int wParam, int lParam); hook int idhook = 0; Is the hook installed? BOOL Ishook = false; GCHandle GC; Private Const int WH_CALLWNDPROC = 4; Hook type global hook//define structure and send structure corresponding to public unsafe struct Ipc_head {public int wversion; public int wpacketsize; public int wmaincmdid; public int wsubcmdid; } Private Const int ipc_buffer = 10240;//Maximum buffer length public unsafe struct Ipc_buffer {public ipc_head Head; Public fixed byte cbbuffer[ipc_buffer]; Where JSON data is stored} public struct COPYDATASTRUCT {public int dwdata; public int cbdata; Public INTPTR lpdata; } void Start () {//Mount Hook hookload (); } void OnDestroy () {//close hook hookclosing (); } private void Hookload () {Debug.Log ("Start Execution"); Installation Hook {//hook entrusted HookProc LPFN = new HookProc (hook); The main module of the associated process is IntPtr hinstance = intptr.zero;//GetModuleHandle (process.getcurrentprocess (). Mainmodule.modulename); Idhook = SetWindowsHookEx (Wh_callwndproc, LPFN, HINSTANCE, (UINT) appdomain.getcurrentthreadid ()); if (Idhook > 0) {Debug.Log ("hooks [" + Idhook + "] successfully installed"); Ishook = true; Keep Active to avoid callback process being garbage collected GC = GCHandle.Alloc (LPFN); } else {Debug.Log ("Hook installation Failed"); Ishook = false; UnhookWindowsHookEx (Idhook); }}}//unload hook private void hookclosing () {if (Ishook) {UnhookWindowsHookEx (id Hook); }} private bool _bcallnext; public bool Callnextproc {get {return _bcallnext;} set {_bcallnext = value;} }//Hook callback private unsafe int hook (int nCode, int wParam, int lParam) {try {IntPtr P = new IntPtr (LParam); Cwpstruct m = (cwpstruct) marshal.ptrtostructure (P, typeof (Cwpstruct)); if (M.message = = 74) { Copydatastruct entries = (copydatastruct) marshal.ptrtostructure ((INTPTR) m.LParam, typeof (Copydatastruct)); Ipc_buffer entries1 = (ipc_buffer) marshal.ptrtostructure ((INTPTR) Entries.lpdata, typeof (Ipc_buffer)); IntPtr intp = new IntPtr (entries1.cbbuffer); String str = new String ((sbyte*) INTP); Debug.Log ("JSON data:" + str); } if (Callnextproc) {return CallNextHookEx (Idhook, NCode, WParam, LParam); } else {//return 1; Return CallNextHookEx (Idhook, NCode, WParam, LParam); }} catch (Exception ex) {Debug.Log (ex). Message); return 0; } }}
OK, all the code is finished in the end. Pack up the Test2.cs scene. Put the Test1.cs code in unity and execute it. Finally look at the Test2.cs EXE in the code took me a long time, very valuable I so share to everyone, I hope you have good things not stingy ah. Hey, finally have not understand can add my Q group 479853988 asked me Oh. There are so many great gods who can ask. Reprint focus on the original OH.
Unity3d process communication using wm_copydate and hooks