성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신</h1> <p> Unity를 닷넷 응용 프로그램에 내장했다면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Unity3D - C# Windows Forms / WPF Application에 통합하는 방법 ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/13584'>https://www.sysnet.pe.kr/2/0/13584</a> </pre> <br /> 아마도 같은 닷넷이니, 직접 닷넷 타입끼리의 연동을 하고 싶을 것입니다.<br /> <br /> 하지만, 아쉽게도 Unity는 Mono 런타임을 사용하므로 우리가 만든 Windows Forms/WPF 측의 호스트가 동작하는 .NET Framework/.NET Core/5+ 환경과 직접적인 연동을 할 수는 없습니다. <br /> <br /> 설령 연동하는 방법을 방법을 제공해 확장 인터페이스를 마련해뒀다고 해도 각각의 런타임이 다르기 때문에 이후 동작 시 필히 문제가 발생합니다. 예를 들어 .NET 8 런타임에서 생성한 참조 개체를 Unity의 Mono 런타임으로 전달하는 경우는 어떨까요? .NET 8 런타임에서 해당 개체를 더 이상 참조하지 않아 GC가 되는 경우 Mono 런타임에 넘겨준 그 개체의 root 참조 유무를 알 수 없어 그냥 제거하게 될 것입니다. 당연히 그럼 Mono 런타임에서는 이미 해제된 참조 개체의 메서드를 호출하는 순간 문제가 발생할 수밖에 없습니다. (나아가, 닷넷 런타임에서 생성한 참조 개체를 Mono 런타임으로 넘겼을 때, 그 참조 개체의 필드에 Mono 런타임에서 생성한 참조를 담는다면 root 참조 문제는 더욱 꼬이게 됩니다.)<br /> <br /> 사실 이전의 .NET Framework CLR조차도 (<a target='tab' href='https://www.sysnet.pe.kr/2/0/10948'>다중 AppDomain</a> 간에 전달한 개체가 있는 경우) AppDomain이 다르면 <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/api/system.marshalbyrefobject?view=net-7.0'>MarshalByRefObject</a>를 이용해 통신해야 했는데, 하물며 런타임이 다른 상황이라면 뭔가 더욱 특별한 방법을 제공해야만 할 것입니다.<br /> <br /> 그렇다면 이제 차선책으로 생각해 볼 수 있는 것이, .NET 수준의 연동이 아니라 COM 인터페이스와 같은 Native 수준의 연동을 기대할 수 있는데, 아쉽게도 Unity는 이에 대해 열어 놓은 것이 없습니다. 현재 유일한 접점으로 볼 수 있는 UnitMain은 뭔가 건네주는 인자가 많은 듯해도,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [DllImport("UnityPlayer.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "UnityMain")] public static extern int UnityMain(IntPtr hInstance, IntPtr hPrevInstance, string lpCmdLine, int nShowCmd) </pre> <br /> 저 인자들 모두 어떤 확장을 위해 제공되는 것이 아니고 단순히 <a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-winmain'>WinMain 진입점</a>과 자연스럽게 연결하기 위한 외부 함수에 지나지 않습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > int __clrcall WinMain( [in] HINSTANCE hInstance, [in, optional] HINSTANCE hPrevInstance, [in] LPSTR lpCmdLine, [in] int nShowCmd ); </pre> <br /> 결국, 어떡해서든 자연스럽게 연동할 수 있는 방법은 없다고 보면 되겠습니다. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 어쩔 수 없습니다. 이렇게 된 이상 같은 프로세스임에도 불구하고 IPC(Inter-Process Communication) 호출에 기대야 합니다. 가령 Socket 통신이 대표적인데요, 단지 소켓은 포트 관리 등의 번거로움이 있으므로 <a target='tab' href='https://www.sysnet.pe.kr/2/0/1751'>기왕이면 Named Pipe 통신</a>이 제어용으로는 나쁘지 않습니다. 아래의 Q&A가 바로 이에 대한 상황을 설명합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Calling Functions on Unity-Application embedded in Winforms-Application [duplicate] ; <a target='tab' href='https://stackoverflow.com/questions/48269904/calling-functions-on-unity-application-embedded-in-winforms-application'>https://stackoverflow.com/questions/48269904/calling-functions-on-unity-application-embedded-in-winforms-application</a> </pre> <br /> 예를 들어, <a target='tab' href='https://www.sysnet.pe.kr/2/0/13584'>지난번</a> 작성한 코드의 WPF 측에 Named Pipe를 열어두는 코드를 다음과 같이 추가할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > { // ...[생략]... private NamedPipeServerStream? _namedPipeServerStream; Thread? _unityThread; Thread? _commThread; private void Window_Loaded(object sender, RoutedEventArgs e) { if (_commThread != null) { return; } _commThread = new Thread(ProxyUnity); _commThread.Start(); } void ProxyUnity() { <span style='color: blue; font-weight: bold'>_namedPipeServerStream = new NamedPipeServerStream("UnityPipe", PipeDirection.InOut, 1 /*, PipeTransmissionMode.Byte, PipeOptions.Asynchronous */); _namedPipeServerStream.WaitForConnection(); StreamString serverStream = new StreamString(_namedPipeServerStream); while (true) { string response = serverStream.ReadString(); if (string.IsNullOrEmpty(response)) { break; } System.Diagnostics.Trace.WriteLine(response); // Unity 측에서 데이터 전송을 하고 있는지 체크하기 위한 디버깅 메시지 출력 } _namedPipeServerStream.Close();</span> } } </pre> <br /> 위의 소스코드에서 사용한 StreamString 도우미 클래스는 다음과 같은데요,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.IO; using System.Text; namespace Assets { /// <summary> /// Simple Wrapper to write / read Data to / from a Named Pipe Stream. /// /// Code based on: /// <a target='tab' href='https://stackoverflow.com/questions/43062782/send-message-from-one-program-to-another-in-unity'>https://stackoverflow.com/questions/43062782/send-message-from-one-program-to-another-in-unity</a> /// </summary> public class StreamString { private Stream ioStream; private UnicodeEncoding streamEncoding; public StreamString(Stream ioStream) { this.ioStream = ioStream; streamEncoding = new UnicodeEncoding(); } public string ReadString() { int len = 0; len = ioStream.ReadByte() * 256; len += ioStream.ReadByte(); byte[] inBuffer = new byte[len]; ioStream.Read(inBuffer, 0, len); return streamEncoding.GetString(inBuffer); } public int WriteString(string outString) { byte[] outBuffer = streamEncoding.GetBytes(outString); int len = outBuffer.Length; if (len > UInt16.MaxValue) { len = (int)UInt16.MaxValue; } ioStream.WriteByte((byte)(len / 256)); ioStream.WriteByte((byte)(len & 255)); ioStream.Write(outBuffer, 0, len); ioStream.Flush(); return outBuffer.Length + 2; } } } </pre> <br /> Unity 프로젝트에서도 저 클래스를 포함하고 WPF 측으로 Named Pipe 연결을 하는 코드를 추가하면 됩니다. 아래는 테스트를 위해 Camera 개체에 스크립트 Component를 연결한 다음 Named Pipe로 WPF 측에 데이터를 주기적으로 쓰는 작업을 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Pipes; using System.Text; using UnityEngine; public class NewBehaviourScript : MonoBehaviour { <span style='color: blue; font-weight: bold'>System.Threading.Thread _task; void Start() { if (_task != null) { return; } _task = new System.Threading.Thread(ThreadFunc); _task.IsBackground = true; _task.Start(); } void ThreadFunc(object arg) { NamedPipeClientStream client = new NamedPipeClientStream(".", "UnityPipe", PipeDirection.InOut, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.None); client.Connect(); StreamString clientStream = new StreamString(client); while (true) { clientStream.WriteString("Hello from UNITY!"); System.Threading.Thread.Sleep(1000); } }</span> // Update is called once per frame void Update() { } } </pre> <br /> 따라서 WPF 프로젝트를 디버깅 모드로 실행하면,<br /> <br /> <img onclick='toggle_img(this)' class='imgView' alt='cs_interop_with_unity_1.png' src='/SysWebRes/bbs/cs_interop_with_unity_1.png' /><br /> <br /> 잘 동작하는군요. ^^ 이후, 양방향 제어는 필요에 따라 코드를 보완하면 끝!<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1769
(왼쪽의 숫자를 입력해야 합니다.)