티스토리 뷰

Code/Hybrid

[Hybride] Visual C++ CLR 사용하기

Hide Code 2010. 4. 22. 08:17




CLRProjectTest.zip

webcamcontrol.zip




Visual Studio를 C++ 컴파일러로 사용하셔도
Common Language Runtime(CLR)을 사용하시는 분은 잘 없으리라고 생각합니다.
일단 배포에도 문제가 있을테고,
굳이 C++ 프로젝트를 CLR을 사용하여 코드를 작성하기보다는
.NET Framework를 사용한다면 처음부터 C# 프로젝트로 생성하여 C#으로 작성하는 것이 훨씬 더 코드 작성에 효율적이기 때문이죠.

그리고 무엇보다도 C++ 에서 CLR 문법이 기존의 C++ 문법에 비해 생소하다는 것입니다.

그러나 CLR을 사용해서 코딩효과가 극대화 되는 경우도 있습니다.

C/C++로 작성된 엔진을 사용할 때인데요.
어떠한 엔진을 사용하는데 Core 기술이라 C 혹은 C++로 작성되어 있는 경우가 있지요?
그러나 UI를 만들기 위해 WIN32나 MFC를 사용하는 것은 요즘은(?) 너무 비용이 많이 든다고 할 수 있습니다.
그래서 UI와 엔진을 분리하고 UI는 C#으로 작성하고 싶을 때가 있습니다.

물론 엔진이 잘 작성되어 있다면
C# 프로젝트에서 [DllImport ]를 사용해서 extern 함수로 맵핑해서 사용하면 되겠지만
엔진에 있는 함수의 파라미터가 C#(CLR)이랑 호환되게 Marchalling 하는 과정은
정말 귀찮은 작업중에 하나이지요.

그래서 저 같은 경우 엔진은 CLR을 사용하지 않고 Native Code로 컴파일하고
엔진을 Wrapping 하는 CLR C++ 프로젝트를 하나 더 만듭니다.

그리고 그 프로젝트를 참조하여 C#에서 사용하지요.
이렇게 하는 것이 여러모로 편리할 때가 있습니다.

그럼 C++을 CLR를 사용하여 컴파일하는 경우 TIP를 몇가지 알아보도록 하겠습니다.

먼저 위의 사진처럼 Common Languae Runtime을 지원하는지를 설정했는지 안했는지를 나타내는 매크로가 있습니다.

_MANAGED 
_M_CEE
// detect_CLR_compilation.cpp
// compile with: /clr
#include <stdio.h>

int main() {
#if (_MANAGED == 1) || (_M_CEE == 1)
printf_s("compiling with /clr\n");
#else
printf_s("compiling without /clr\n");
#endif
}

위의 코드처럼 _MANAGED와 _M_CEE 매크로를 사용하면 프로젝트 속성이 어떤지를 알 수 있습니다.

이제 본격적으로 몇가지를 알아보도록 하겠습니다.

아래와 같이 CLRProject와 CShapFormsTest 프로젝트를 두가지 만듭니다.
CLRProject는 Visual Studio의 Project Template에서 Visual C++ 카테고리에 CLR 아래에 있는 Class Library를 선택하고
CSharpFormsTest는 Visual C# 카테고리에 Windows Forms Application을 선택합니다.



그림과 같이 솔루션이 구성되었겠죠?

이제 CLRProjectTest에서 미리 생성되어 있는 Class1을 가지고
테스트를 몇 가지 해보도록 하죠.

WinForm에서 TextBox에 글자를 입력하고 버튼을 누르면
CLRProject에서 Console::WriteLine이 아닌 wprintf 함수를 사용하여
콘솔에 출력하는 것을 작성해보도록 하겠습니다.

일단은 WinForm에서는 System.String 타입으로 스트링을 넘기고 싶으니
c++ CLR Project에서는 System::String^ 으로 받아야 겠지요.




// CLRProjectTest.h

#pragma once

#include <vcclr.h> // for PtrToStringChars
#include <stdio.h> // for wprintf

using namespace System;

namespace CLRProjectTest {

public ref class Class1
{
public:
void TestFunc1(String^ clrStr)
{
pin_ptr<const wchar_t> wchStr = PtrToStringChars(clrStr);

wprintf(wchStr);
}
};
}

위와 같이 하면 한글이 출력이 안되는군요.
이럴 때는 #include <atlbase.h>를 추가하시고 아래와 같이 하시면 됩니다.

        void TestFunc1(String^ clrStr)
{
USES_CONVERSION;
pin_ptr<const wchar_t> wchStr = PtrToStringChars(clrStr);

printf(W2A(wchStr));
}

그리고 위에 생성된 Class1을 CShatFormsTest에서는 아래와 같이 사용합니다.

먼저 CShapFormsTest에 Referces를 추가하는데요.
아래와 같이 Projects에서 CLRProjectTest 프로젝트를 추가하시면 되겠죠?



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CSharpFormsTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
CLRProjectTest.Class1 obj1 = new CLRProjectTest.Class1();
obj1.TestFunc1(str);
}
}
}

그리고 위와 같이 CLRProjectTest.Class1 ob1 = new CLRProjectTest.Class1() 이렇게 객체를 생성하시고 함수를 호출하시면 됩니다.

여기서 가장 중요한 점은 CSharp에서 사용한 System.String 객체를 wchar로 변경하는 법인데요.

<vcclr.h> 에 있는 PtrToStringChars 함수를 사용하셔도 되고.

using namespace std;
void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}

위의 방법처럼 std::string으로 변경할 수도 있습니다.

만약에 return C++ 프로젝트에서 return 한 값이 문자열이고 이것을 WinForm에서 받는 법은 어떻게 할까요?

        String^ TestFunc2(String^ clrStr)
{
pin_ptr<const wchar_t> wchStr = PtrToStringChars(clrStr);

std::wstring modifiedString(L"output : ");
modifiedString.append(wchStr);

return gcnew String(modifiedString.c_str());
}
TestFunc2와 같이 파라미터로 받은 String^을 조작하여 String^로 되돌려 주는 함수가 있다고 가정합니다.

return 값을 위해 unmanaged char 배열을 그냥 gcnew String() 하시면 자동으로 변환되니까, 사용하시기 편하실 겁니다.

        private void button2_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
CLRProjectTest.Class1 obj1 = new CLRProjectTest.Class1();
string str2 = obj1.TestFunc2(str);
textBox1.Text = str2;
}

WinForm에서는 TestFunc1 과 마찬가지로 TestFunc2를 같은 방법으로 사용하시면 되구요.

이번에는 약간 어려운(?) 작업을 해보겠습니다.

함수 return에 스트링을 위와 같이 전달하는 방식은 쉬운데, CShap에서 파라미터에 out을 추가하여 파라미터를 전달하는 방법은 어떻게 할까요?

void TestFunc3(int a, int b, [Runtime::InteropServices::Out] String^ %add,
 [Runtime::InteropServices::Out] String^ %minus)
{
wchar_t addStr[128];
wsprintf(addStr, L"%d", a+b);
add = gcnew String(addStr);

wchar_t minusStr[128];
wsprintf(minusStr, L"%d", a-b);
minus = gcnew String(minusStr);
}

위의 함수는 정수형 타입 2개를 받아서 두 값의 더한 값을 표현한 스트링 하나와 두 값을 뺀 값을 표현한 스트링 하나를 out 방식으로 전달하는 방법을 사용하였습니다.

흔히 C#에서 [DllImport] 저런 기능을 하려면 이것 저것 많이 생각해야 하는데, 위의 방식이 훨씬 편하지 않나요?

        private void button3_Click(object sender, EventArgs e)
{
string aStr = textBox2.Text;
string bStr = textBox3.Text;
CLRProjectTest.Class1 obj1 = new CLRProjectTest.Class1();

string addStr;
string minusStr;
int a = 0;
int b = 0;
if (int.TryParse(aStr, out a) && int.TryParse(bStr, out b))
{
obj1.TestFunc3(a, b, out addStr, out minusStr);
textBox1.Text = string.Format("Add : {0}, Minus: {1}", addStr, minusStr);
}
}
 

TestFunc3를 WinForm에서 사용하는 방법은 위와 같습니다.

그리고 이것은 하나의 팁인데 문자열을 위와 같이 int.Parse 함수대신 int.TryParse를 사용하면 코드가 더 견고해집니다.

 

그럼 CSharp에서 사용중인 배열을 넘기는 방법은 무엇일까요?

WinForm에서 숫자 배열을 넘기고 C++에서는 새로운 배열을 만들고 전달 받았던 배열의 모든 요소에 1000을 나눈 값을 저장하는
함수가 필요하다고 해봅시다.

        void TestFunc4(array<int>^ arr, int capacity, [Runtime::InteropServices::Out] array<int>^ %b)
{
array<int>^ nums = gcnew array<int>(capacity);
for(int i=0; i<capacity; i++)
{
nums[i] = arr[i] / 1000;
}

b = nums;
}
clr 배열을 C++에서 받는 법은 위처럼 array<int>^ 로 하시면 됩니다.
       private void button4_Click(object sender, EventArgs e)
{
Random random = new Random(DateTime.Now.Second);
int[] arr = new int[5];
int[] output = null;
for (int i = 0; i < arr.Length; i++)
{
arr[i] = random.Next();
}

CLRProjectTest.Class1 obj1 = new CLRProjectTest.Class1();

obj1.TestFunc4(arr, arr.Length, out output);
}

그리고 C#에서는 위와 같이 사용하시면 됩니다.

이번에는 아주 고난도(?)의 예제로서 WPF에서 C++에서 생성한 창을 임베딩하는 방법을 알아보겠습니다.

WPF에서 WebCam 사용하기 에서 소개드렸었는데요.

소스를 잠깐 살펴보도록 하겠습니다.

using namespace System;
using namespace System::Windows;
using namespace System::Windows::Interop;
using namespace System::Runtime::InteropServices;

namespace WebCamControl {

//Derive from HwndHost
public ref class WebCamClass : public HwndHost
{
public:
//Constructor
WebCamClass() {
pConnector = NULL;
}

//Start the preview
void Start() {
if(pConnector != NULL)
pConnector->Start();
}

//... other functions

//We get called on this function when the final size of the WPF control is known
virtual Size ArrangeOverride(Size finalSize) override {
//Use the size to correctly shape the video window to the control
pConnector->FinalizeLayout(finalSize.Width,finalSize.Height);
//We arn't changing anything about the WPF control size
return finalSize;
}

//We get called on this fucntion when WPF is building the control
virtual HandleRef BuildWindowCore(HandleRef hwndParent) override {
//Create our own window that is child of the WPF window and a parent to the video window
//It allows us to more closly control the behaviour of the video window
HWND handle = CreateWindowEx(0, L"Static",
NULL,
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN,
0, 0, // x, y
20,20, // height, width
(HWND) hwndParent.Handle.ToPointer(), // parent hwnd
0, // hmenu
0, // hinstance
0); // lparam

//Create our unmanaged connection class
pConnector = new DShowConnector();

//Call setup to build the graph, passing the window we want as parent
if(!pConnector->Setup(handle))
{
pConnector->Cleanup();
throw gcnew Exception("Could not connect to Web Cam");
}

//Return our created window
return HandleRef(this, IntPtr(handle));
}

virtual void DestroyWindowCore(HandleRef hwnd) override {
//Tear down dshow graph
pConnector->Cleanup();

//Delete the class
delete pConnector;
}

private:
//Unmanaged pointer
DShowConnector *pConnector;
};
}

위의 Class는 HwndHost를 상속받아서 WPF의 Element로 아래와 같이 사용가능 합니다.


    public partial class Window1 : Window
{
WebCamControl.WebCamClass host = null;

public Window1()
{
InitializeComponent();
host = new WebCamControl.WebCamClass();
insertHwndHere.Child = host;
}

void StartClicked(object sender, EventArgs e)
{
host.Start();
}
}
 

DShowConnector 라는 Class는 DirectShow 필터를 구성하고 VideoWindows를 생성하는 역할을 합니다.
DirectShow는 일반적인 COM 프로그래밍 방식으로 사용해야 하기 때문에 C++이 일반적이지요.

위와 같이 managed code와 unmanged code를 왔다갔다 하는 일은 C#이 대중화 되면서
빈번하게 필요합니다.

이제 좀더 C#을 더욱 잘 쓸 수 있게 C++ 프로젝트에 CLR에 친숙해 보는 것도 어떨까 합니다.


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함