๐ฏ C++์์ PowerShell์ C++/CLI DLL์ ํตํด ์คํํ๋ ๋ฐฉ๋ฒ (Visual Studio 2022 / C++)
โ
์ ์ฒด ๊ตฌ์กฐ
๐น โ CLI ๋ํผ DLL (C++/CLI)
PowerShell ์คํฌ๋ฆฝํธ๋ฅผ ์คํํ๋ ๊ธฐ๋ฅ์ ์ ๊ณตํฉ๋๋ค.
๐น โก ๋ค์ดํฐ๋ธ C++ ํธ์ถ์
CLI DLL์ ํธ์ถํ์ฌ PowerShell ์คํฌ๋ฆฝํธ๋ฅผ ์คํํฉ๋๋ค.
๐ง ๋จ๊ณ 1: CLI ๋ํผ DLL ํ๋ก์ ํธ ์์ฑ
1. ํ๋ก์ ํธ ์์ฑ
- [์๋ก ๋ง๋ค๊ธฐ] โ [C++] โ CLR ํด๋์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ (.NET Framework)
- ์ด๋ฆ๏ผ
PowerShellWrapper
๐ก ์ด ํ
ํ๋ฆฟ์ด ํ์๋์ง ์๋ ๊ฒฝ์ฐ, “.NET ๋ฐ์คํฌํฑ ๊ฐ๋ฐ” ์ํฌ๋ก๋๋ฅผ ์ค์นํ์ธ์.
2. NuGet ํจํค์ง ์ถ๊ฐ
- ํ๋ก์ ํธ ์ฐํด๋ฆญ โ [NuGet ํจํค์ง ๊ด๋ฆฌ]
System.Management.Automation ๊ฒ์ ๋ฐ ์ค์น
(๋ฒ์ 5.x ๋๋ 7.x)
3. CLI ์ธก ์ฝ๋ ๊ตฌํ
PowerShellWrapper.h
1
2
3
4
5
6
7
8
9
10
| #pragma once
using namespace System;
namespace PowerShellWrapper {
public ref class PowerShellExecutor {
public:
String^ Execute(String^ script);
};
}
|
PowerShellWrapper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| #include "PowerShellWrapper.h"
using namespace System;
using namespace System::Management::Automation;
using namespace System::Collections::ObjectModel;
String^ PowerShellWrapper::PowerShellExecutor::Execute(String^ script)
{
PowerShell^ ps = PowerShell::Create();
ps->AddScript(script);
Collection<PSObject^>^ results = ps->Invoke();
System::Text::StringBuilder^ sb = gcnew System::Text::StringBuilder();
for each (PSObject^ result in results)
{
sb->AppendLine(result->ToString());
}
return sb->ToString();
}
|
๐ง ๋จ๊ณ 2: ๋ค์ดํฐ๋ธ C++ ์ธก์์ ํธ์ถ
1. C++ ์ฝ์ ์ฑ ํ๋ก์ ํธ ์์ฑ
2. ์ฐธ์กฐ ์ค์
- ํ๋ก์ ํธ ์ฐํด๋ฆญ โ [์ฐธ์กฐ ์ถ๊ฐ] โ [ํ๋ก์ ํธ] โ
PowerShellWrapper ์ถ๊ฐ - [๊ตฌ์ฑ ์์ฑ] โ [C/C++] โ [๊ณต์ฉ ์ธ์ด ๋ฐํ์ ์ง์] โ /clr ๋ก ๋ณ๊ฒฝ
3. ์คํ ์ฝ๋ (main.cpp)
1
2
3
4
5
6
7
8
9
10
11
12
13
| #using <System.dll>
#using "..\\PowerShellWrapper\\Debug\\PowerShellWrapper.dll"
using namespace System;
using namespace PowerShellWrapper;
int main()
{
PowerShellExecutor^ executor = gcnew PowerShellExecutor();
String^ result = executor->Execute("Get-Process | Select-Object -First 1");
Console::WriteLine(result);
return 0;
}
|
- ์ด ๊ตฌ์ฑ์ COM์ด ์๋ .NET DLL์ ์ง์ ์ฐธ์กฐํ๋ ๋ฐฉ์์ด๋ฏ๋ก, IDL์ด๋ TLB, COM ๋ฑ๋ก์ด ํ์ํ์ง ์์ต๋๋ค.
โ
์ต์ข
๊ตฌ์ฑ
1
2
3
4
5
| Solution
โโโ PowerShellWrapper (C++/CLI DLL)
โ โโโ PowerShellExecutor
โโโ NativeApp (C++ EXE)
โโโ main.cpp โ DLL ํธ์ถ
|