Microsoft MVP성태의 닷넷 이야기
VC++: 37. XmlCodeGenerator를 C/C++ 코드 생성에 적용 [링크 복사], [링크+제목 복사],
조회: 39858
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)

XmlCodeGenerator를 C/C++ 코드 생성에 적용


XmlCodeGenerator에 대해서는 가끔씩 설명을 드렸지요. (개인적으로, 사실 엄청 잘 쓰고 있는 자작 툴입니다. ^^)

XML/XSLT로 구현하는 매크로 확장 
; https://www.sysnet.pe.kr/2/0/542

XmlCodeGenerator 1.0.0.4 업데이트
; https://www.sysnet.pe.kr/2/0/760

아쉬운 점이 하나 있다면, 이런 CodeGenerator 사용자 정의 툴이 Managed 언어를 다루는 프로젝트에서만 적용된다는 점입니다. 굳이 이런 제한을 둘 필요가 있었을까 싶지요!

오늘은, 문득 이에 대한 해결책이 생각났습니다.

간단합니다. 코드 생성하는 파일들은 그냥 C# 프로젝트에 넣어버리고, C++ 프로젝트에서는 상대 경로를 include하는 것으로 해당 코드들을 그냥 포함해 버리는 것입니다. 이렇게 되면, 심지어 소스 컨트롤을 연결해서 관리하는 것에도 문제가 없습니다. 실제로 한번 따라해 볼까요? ^^




1. XML 파일 생성


자신의 코드에서 복잡하게/반복적으로 사용되는 코드를 간단하게 관리할 수 있는 XML 파일을 만듭니다.

<?xml version="1.0" encoding="utf-8" ?>

<people>
  
  <person name="Tester" age="15" />
  <person name="Administrator" age="17" />
  
</people>

2. XSLT 파일 생성


XML 파일의 내용을 C/C++ 코드로 만들어 줄 XSLT 파일을 만듭니다.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  xmlns:xcg="https://www.sysnet.pe.kr/WPFClassMemberDef"
>
    <xsl:param name="XCG_CurrentTime"/>
    <xsl:output method="text" encoding="utf-8" indent="yes"></xsl:output>

    <xsl:template match="people">

/*
Created: <xsl:value-of select="$XCG_CurrentTime" />
*/

#if defined (HEADER_DECLARATION)

#if !defined __CPP_ARRAY_H
#define __CPP_ARRAY_H

typedef struct tagPerson
{
  wstring Name;
  int Age;
} Person;

extern vector <xsl:text disable-output-escaping="yes">&lt;</xsl:text>Person *<xsl:text disable-output-escaping="yes">&gt;</xsl:text> g_people;
void InitializePeople();

#endif

#endif

#if defined (IMPLEMENTATION_DEFINITION)

vector <xsl:text disable-output-escaping="yes">&lt;</xsl:text>Person *<xsl:text disable-output-escaping="yes">&gt;</xsl:text> g_people;

void InitializePeople()
{
  <xsl:for-each select="person">
    {
      Person *pItem = new Person();
      pItem-<xsl:text disable-output-escaping="yes">&gt;</xsl:text>Name = L"<xsl:value-of select="@name" />";
      pItem-<xsl:text disable-output-escaping="yes">&gt;</xsl:text>Age = <xsl:value-of select="@age" />;
      g_people.push_back(pItem);
    }
  </xsl:for-each>
}

#endif
  </xsl:template>

</xsl:stylesheet>


3. XmlCodeGenerator 적용


생성한 XML 파일과 XSLT 파일을 C# 프로젝트에 추가하고, XML 파일의 "Custom Tool" 속성을 "XmlCodeGenerator"로 지정해 줍니다.

[그림 1: XmlCodeGenerator 적용]
cpp_xmlcodegen_1.png

그러면, "그림 1"에서 보는 것처럼 XML 파일 하위에 .cs 파일이 생성됩니다. CS 파일의 내용은 C/C++에서 사용될 수 있는 코드로 다음과 같이 생성됩니다.

/*
Created: 09/13/2009 21:19:05
*/

#if defined (HEADER_DECLARATION)

#if !defined __CPP_ARRAY_H
#define __CPP_ARRAY_H

typedef struct tagPerson
{
  wstring Name;
  int Age;
} Person;

extern vector <Person *> g_people;
void InitializePeople();

#endif

#endif

#if defined (IMPLEMENTATION_DEFINITION)

vector <Person *> g_people;

void InitializePeople()
{
  
    {
      Person *pItem = new Person();
      pItem->Name = L"Tester";
      pItem->Age = 15;
      g_people.push_back(pItem);
    }
  
    {
      Person *pItem = new Person();
      pItem->Name = L"Administrator";
      pItem->Age = 17;
      g_people.push_back(pItem);
    }
  
}

#endif

매크로 상수를 이용해서 하나의 CS 파일 안에 C/C++ 헤더 파일과 코드에서 사용될 수 있도록 하고 있습니다.

C# 프로젝트에서는 위의 CS 파일이 빌드되면 오류가 발생하기 때문에 CS 파일에 대해서는 컴파일 옵션을 "None"으로 해줍니다.

[그림 2: Build Action - None 적용]
cpp_xmlcodegen_2.png

4. 생성된 CS 파일을 C/C++ 프로젝트에서 사용


이제, C/C++ 프로젝트에서 #include를 이용해서 해당 파일들을 포함시켜 줍니다. 간단하게는 stdafx.h/stdafx.cpp 파일에서 각각 다음과 같이 추가시켜주면 되겠지요. ^^

======== stdafx.h ==========

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#include <string>
#include <vector>

using namespace std;

#define HEADER_DECLARATION
#include "..\CppTestCodeGenerator\CppArray.cs" 


======== stdafx.cpp ========

#include "stdafx.h"

#undef HEADER_DECLARATION
#define IMPLEMENTATION_DEFINITION
#include "..\CppTestCodeGenerator\CppArray.cs" 




이제부터는 Person이라는 코드를 관리하기 위해 C/C++ 코드를 찾아가서 수정할 필요 없이 해당 XML 파일을 수정함으로써 편리하게 코드에 결과를 반영할 수 있습니다. 위에서는 단순하게 예를 들었지만, 복잡하게/반복적으로 초기화되는 코드를 위의 자동 생성 코드로 치환해 두면 자칫 실수할 수 있는 오류 횟수를 많이 줄일 수 있습니다.

사실... 시간이 지났을 때, C/C++ 코드를 다시 보면서 코드를 추가하는 것보다 XML로 추가하는 것이 더욱 직관적이죠. 초보적인 수준이긴 하지만 이것도 DSL(Domain Specific Language)이라고 할 수 있지 않을까요!

첨부된 파일은 위의 예제를 테스트한 프로젝트입니다.



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/11/2022]

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

비밀번호

댓글 작성자
 



2009-11-25 04시23분
[이유진] 프로젝트 실행을 해봤는데 명령 프롬포트 창이 한번 켜졌다 사라지고 끝이네요; 원래 이런가요?^^
[guest]
2009-11-26 09시38분
첨부된 프로젝트 파일을 실행시키셨나요? 사실 그건 별로 의미가 없는데요. ^^ 위의 글이 의미가 있는 것은, 프로젝트에 포함된 XML 파일을 Visual Studio 에서 변경하고 저장했을 때 CS 파일이 덩달아 업데이트 된다는 점입니다. 글의 도입에 소개한 "XML/XSLT 로 구현하는 매크로 확장" 과 "XmlCodeGenerator 1.0.0.4 업데이트" 편을 읽어보시면 이해가 되실 것입니다.
kevin25

... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12416정성태11/19/202017439오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202017560.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202019768VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202018687.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202020784.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202017544오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202017771디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019592.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034841도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019965.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020912.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018914.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019516.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018304.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019891.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202019181VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015355오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018789.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018475오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018517.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015433VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202018290오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015924오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015444오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019978.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019763디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...