Calling a C# library from python Calling a C# library from python python python

Calling a C# library from python


It is actually pretty easy. Just use NuGet to add the "UnmanagedExports" package to your .Net project. See https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports for details.

You can then export directly, without having to do a COM layer. Here is the sample C# code:

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;using RGiesecke.DllExport;class Test{    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]    public static int TestExport(int left, int right)    {        return left + right;    }}

You can then load the dll and call the exposed methods in Python (works for 2.7)

import ctypesa = ctypes.cdll.LoadLibrary(source)a.add(3, 5)


Since your post is tagged IronPython, if you want to use the sample C# the following should work.

import clrclr.AddReference('assembly name here')from DataViewerLibrary import PlotData p = PlotData()p.Start()


Python for .Net (pythonnet) may be a reasonable alternative to IronPython in your situation.https://github.com/pythonnet/pythonnet/blob/master/README.rst

From the site:

Note that this package does not implement Python as a first-class CLR language - it does not produce managed code (IL) from Python code. Rather, it is an integration of the CPython engine with the .NET runtime. This approach allows you to use use CLR services and continue to use existing Python code and C-based extensions while maintaining native execution speeds for Python code.

Also

Python for .NET uses the PYTHONPATH (sys.path) to look for assemblies to load, in addition to the usual application base and the GAC. To ensure that you can implicitly import an assembly, put the directory containing the assembly in sys.path.

This package still requires that you have a local CPython runtime on your machine.See the full Readme for more info https://github.com/pythonnet/pythonnet