추후 실무 간, Python + C# 연동해서 PJT를 진행 할 날이 올 것 같아 미리 포스팅해서 내용 정리 해보려고 합니다!
설치 및 기본 예제 코드는 StackOverFlow - GitHub 에서 주로 참고해서 블로그 작성했습니다.
▶ Language : C#, Python
▶ IDE : Visual Studio 2017, Visual Studio Code
▶ 설치 방법
- IronPython 설치
- NuGet 패키지 관리
- C# - Python 연동 Code
using System;
using IronPython;
using IronPython.Modules;
using IronPython.Hosting;
using IronPython.Runtime;
// Python Engine Create
var engine = IronPython.Hosting.Python.CreateEngine();
// Python Scope Create
var scope = engine.CreateScope();
try
{
// Python File Read
// test.py 실제 경로
var source = engine.CreateScriptSourceFromFile("test.py");
// source(Python File Reading) - Scope Input - Run
source.Execute(scope);
// Function return
var getPythonFunc = scope.GetVariable<Func<string>>("getHello"); // test.py Reading 시, Print(~)
Console.WriteLine("def 실행 테스트 : " + getPythonFunc()); // result - Hello
// int 매개 변수 2ea, return type (int)
var sum = scope.GetVariable<Func<int, int, int>>("sum");
Console.WriteLine("def 실행 테스트 : " + sum(2, 3)); // result - 5
// class return
var getPython = scope.GetVariable("getObject")(1, 2);
// getObject - sum func run
Console.WriteLine("def 실행 테스트 : " + getPython.sum()); // result - 3
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
'Language - C# > C#(문법)' 카테고리의 다른 글
Python & C# 이용한 Socket 통신 (0) | 2021.11.10 |
---|---|
C# - Visual Studio Python 연동 - 2 (0) | 2021.11.10 |
C# - Effective C# 개정판, 매개 변수 (0) | 2021.11.08 |
C# - Coding, Naming Convention (0) | 2021.11.08 |
C# - Enum.Parse, Enum.TryParse (0) | 2021.11.08 |