Microsoft MVP성태의 닷넷 이야기
닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [링크 복사], [링크+제목 복사],
조회: 10840
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 3개 있습니다.)
개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
; https://www.sysnet.pe.kr/2/0/13581

개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법
; https://www.sysnet.pe.kr/2/0/13584

닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신
; https://www.sysnet.pe.kr/2/0/13588




C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신

Unity를 닷넷 응용 프로그램에 내장했다면,

Unity3D - C# Windows Forms / WPF Application에 통합하는 방법
; https://www.sysnet.pe.kr/2/0/13584

아마도 같은 닷넷이니, 직접 닷넷 타입끼리의 연동을 하고 싶을 것입니다.

하지만, 아쉽게도 Unity는 Mono 런타임을 사용하므로 우리가 만든 Windows Forms/WPF 측의 호스트가 동작하는 .NET Framework/.NET Core/5+ 환경과 직접적인 연동을 할 수는 없습니다.

설령 연동하는 방법을 방법을 제공해 확장 인터페이스를 마련해뒀다고 해도 각각의 런타임이 다르기 때문에 이후 동작 시 필히 문제가 발생합니다. 예를 들어 .NET 8 런타임에서 생성한 참조 개체를 Unity의 Mono 런타임으로 전달하는 경우는 어떨까요? .NET 8 런타임에서 해당 개체를 더 이상 참조하지 않아 GC가 되는 경우 Mono 런타임에 넘겨준 그 개체의 root 참조 유무를 알 수 없어 그냥 제거하게 될 것입니다. 당연히 그럼 Mono 런타임에서는 이미 해제된 참조 개체의 메서드를 호출하는 순간 문제가 발생할 수밖에 없습니다. (나아가, 닷넷 런타임에서 생성한 참조 개체를 Mono 런타임으로 넘겼을 때, 그 참조 개체의 필드에 Mono 런타임에서 생성한 참조를 담는다면 root 참조 문제는 더욱 꼬이게 됩니다.)

사실 이전의 .NET Framework CLR조차도 (다중 AppDomain 간에 전달한 개체가 있는 경우) AppDomain이 다르면 MarshalByRefObject를 이용해 통신해야 했는데, 하물며 런타임이 다른 상황이라면 뭔가 더욱 특별한 방법을 제공해야만 할 것입니다.

그렇다면 이제 차선책으로 생각해 볼 수 있는 것이, .NET 수준의 연동이 아니라 COM 인터페이스와 같은 Native 수준의 연동을 기대할 수 있는데, 아쉽게도 Unity는 이에 대해 열어 놓은 것이 없습니다. 현재 유일한 접점으로 볼 수 있는 UnitMain은 뭔가 건네주는 인자가 많은 듯해도,

[DllImport("UnityPlayer.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "UnityMain")]
public static extern int UnityMain(IntPtr hInstance, IntPtr hPrevInstance, string lpCmdLine, int nShowCmd)

저 인자들 모두 어떤 확장을 위해 제공되는 것이 아니고 단순히 WinMain 진입점과 자연스럽게 연결하기 위한 외부 함수에 지나지 않습니다.

int __clrcall WinMain(
  [in]           HINSTANCE hInstance,
  [in, optional] HINSTANCE hPrevInstance,
  [in]           LPSTR     lpCmdLine,
  [in]           int       nShowCmd
);

결국, 어떡해서든 자연스럽게 연동할 수 있는 방법은 없다고 보면 되겠습니다. ^^




어쩔 수 없습니다. 이렇게 된 이상 같은 프로세스임에도 불구하고 IPC(Inter-Process Communication) 호출에 기대야 합니다. 가령 Socket 통신이 대표적인데요, 단지 소켓은 포트 관리 등의 번거로움이 있으므로 기왕이면 Named Pipe 통신이 제어용으로는 나쁘지 않습니다. 아래의 Q&A가 바로 이에 대한 상황을 설명합니다.

Calling Functions on Unity-Application embedded in Winforms-Application [duplicate]
; https://stackoverflow.com/questions/48269904/calling-functions-on-unity-application-embedded-in-winforms-application

예를 들어, 지난번 작성한 코드의 WPF 측에 Named Pipe를 열어두는 코드를 다음과 같이 추가할 수 있습니다.

{
    // ...[생략]...
    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()
    {
        _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();
    }
}

위의 소스코드에서 사용한 StreamString 도우미 클래스는 다음과 같은데요,

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:
    /// https://stackoverflow.com/questions/43062782/send-message-from-one-program-to-another-in-unity
    /// </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;
        }
    }
}

Unity 프로젝트에서도 저 클래스를 포함하고 WPF 측으로 Named Pipe 연결을 하는 코드를 추가하면 됩니다. 아래는 테스트를 위해 Camera 개체에 스크립트 Component를 연결한 다음 Named Pipe로 WPF 측에 데이터를 주기적으로 쓰는 작업을 합니다.

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

    // Update is called once per frame
    void Update()
    {

    }
}

따라서 WPF 프로젝트를 디버깅 모드로 실행하면,

cs_interop_with_unity_1.png

잘 동작하는군요. ^^ 이후, 양방향 제어는 필요에 따라 코드를 보완하면 끝!




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 3/28/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2024-04-23 10시26분
안녕하세요 좋은글 감사합니다.
 현재 제가 wpf로 관제 모니터링 시스템을 만들고 있는 초보 개발자입니다. 너무 밋밋해서 3d를 생각하다 unity 엔진을 사용해서 디지털 트윈 형식으로 만들어 볼까 생각 중인데요,
연동이 자연스럽지 않다고 하셨는데 혹시 제가 생각한 방법으로 시스템을 만들기 부적합할까요? 데이터 통신은 약 200/msec 간격으로 데이터를 주고받을 생각입니다.
공진영
2024-04-23 10시33분
만드실 수 있습니다. 단지, Unity 엔진 내의 스크립트와 WPF 내에서의 코드가 별도의 IPC 통신을 맺어서 처리해야 하는 번거로움이 있을 뿐입니다.

어찌 보면, 경우에 따라 응용 프로그램이 커졌을 때 프로세스를 나눠 서로 클라이언트/서버 통신하는 경우도 있을 테니, 그런 것을 감안해 보면 '번거로움'이라기보다는 그냥 필요한 작업이라고 여길 수도 있을 것입니다. ^^;

(로컬 PC 내에서의 통신에서 200/msec는 문제가 되지 않습니다.)
정성태

... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11836정성태3/5/201923350오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921834.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920636개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921185개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917096오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916924오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916623오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918322개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926213개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919143오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919329오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924599개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201919041오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920649오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918981오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919735오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922807오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922068Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920157VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916519오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919979Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918188오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201917067오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918354.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915687오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920921오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...