从python调用C#库

时间:2011-09-09 22:10:41

标签: c# python interop ironpython python.net

任何人都可以分享如何从python代码调用一个简单的C#库(实际上是它的WPF)的工作示例? (我已经尝试过使用IronPython,并且在我的python代码使用不受支持的CPython库时遇到了太多麻烦所以我想尝试反过来并从Python调用我的C#代码)。

以下是我正在玩的例子:

using System.Runtime.InteropServices;
using System.EnterpriseServices;

namespace DataViewerLibrary
{
    public interface ISimpleProvider
    {
       [DispIdAttribute(0)]
       void Start();
    }

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class PlotData : ServicedComponent, ISimpleProvider
    {
       public void Start()
       {
          Plot plotter = new Plot();
          plotter.ShowDialog();
       }
    }
}

绘图仪是一个绘制椭圆的WPF窗口

我不知道如何从我的python中调用此代码。有什么建议?

5 个答案:

答案 0 :(得分:33)

实际上很容易。只需使用NuGet添加" UnmanagedExports"打包到您的.Net项目。有关详细信息,请参阅https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports

然后您可以直接导出,而无需进行COM层。以下是C#代码示例:

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;
    }
}

然后,您可以加载dll并在Python中调用公开的方法(适用于2.7)

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

答案 1 :(得分:16)

由于您的帖子被标记为IronPython,如果您想使用示例C#,则以下内容应该有效。

import clr
clr.AddReference('assembly name here')
from DataViewerLibrary import PlotData 

p = PlotData()
p.Start()

答案 2 :(得分:11)

在你的情况下,用于.Net(pythonnet)的Python可能是IronPython的合理替代品。 https://github.com/pythonnet/pythonnet/blob/master/README.md

来自网站:

  

请注意,此程序包不会将Python实现为第一类CLR   language - 它不会从Python代码生成托管代码(IL)。   相反,它是CPython引擎与.NET的集成   运行。此方法允许您使用CLR服务并继续   在维护时使用现有的Python代码和基于C的扩展   Python代码的本机执行速度。

另外

  

Python for .NET使用PYTHONPATH(sys.path)来查找程序集   加载,除了通常的应用程序基础和GAC。至   确保您可以隐式导入程序集,放置目录   包含sys.path中的程序集。

此程序包仍然要求您的计算机上有本地CPython运行时。 有关详细信息http://pythonnet.github.io/readme.html

,请参阅完整自述文件

答案 3 :(得分:7)

这个项目是为了这个目的而开发的 - 在常规Python中使用C#类

https://bitbucket.org/pydotnet/pydotnet/wiki/Home

您需要做的就是在CPython中安装MSI或EGG。 PyDotnet是Python模块,因此可执行文件从Python或Anaconda的安装中保留常规python.exe。支持32位和64位。

无限制地访问所有C#类,包含output和ref参数的方法,泛型类和泛型方法,扩展方法,私有成员。

使用自定义机制重载装配加载程序以搜索装配体。

.NET运行时类型信息可转换为类对象,可以将其实例化为任何其他类。

特别为Python交互式shell设计的特殊导入模式,它允许您发现可用的程序集,命名空间,类,方法等。

我在等待反馈:)

答案 4 :(得分:2)

我不是.NET专家,但您的代码看起来好像您的方法是作为COM对象公开的。因此,您可以尝试http://starship.python.net/crew/mhammond/win32/包来访问它。