Skip to content

s4lt3d/IronPythonExamples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 

Repository files navigation

IronPython Integration Examples

Demonstrations of embedding Python scripts in C# applications using IronPython, with examples of data exchange and interop.


Overview

This repository shows how to integrate Python scripts directly into C# applications using IronPython. Two primary examples illustrate different use cases.


Installation

Add IronPython to your C# project via NuGet:

Install-Package IronPython -Version 2.7.10

Example 1: Getting a List from Python into C#

File: getting_a_list.cs

This example demonstrates:

  • Executing Python code from C# that generates a list of squared numbers
  • Retrieving variables from the executed Python script
  • Converting Python lists to C# collections

Highlights:

  • Python script uses list comprehension to create x_squared
  • List is retrieved in C# and converted to a C# List
  • Values are printed from C# side

Example 2: Calling C# Functions from Python

File: calling_cs_function_example.cs

This example demonstrates:

  • Executing Python code from C#
  • Using C# functions within Python scripts
  • Retrieving variables created in Python

Highlights:

  • Python script uses C# function log() (alternative to Python's print)
  • Python calls custom C# function custom_add()
  • Variables created in Python (x, y) are accessed from C# side

Key Features

  • Data Exchange — Pass data between Python and C#
  • Function Interop — Call C# functions from Python
  • Embedded Scripts — Define Python code as strings in C#

Usage

Running the Examples

  1. Create a new C# console application in Visual Studio
  2. Install IronPython via NuGet: Install-Package IronPython -Version 2.7.10
  3. Copy one of the example files into your project
  4. Build and run

Basic Structure

Each example follows this pattern:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

// Create Python engine
var engine = Python.CreateEngine();

// Execute Python code as string
engine.Execute(@"
    # Python code here
");

// Access variables from C#
var result = engine.GetVariable("variable_name");

Architecture

  • Engine Layer — IronPython runtime that interprets Python code
  • Scope Layer — Variable namespace where Python variables live
  • Interop Layer — Bridges between C# objects and Python code

Dependencies

  • IronPython 2.7.10 — Install via NuGet
  • .NET Framework — 4.0 or higher

License

Copyright © [Author Name]

About

IronPython Integration with C#

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages