从python调用C#库

ych*_*uri 39 c# python ironpython interop 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();
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 34

这实际上非常简单.只需使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

import ctypes
a = ctypes.cdll.LoadLibrary(source)
a.add(3, 5)
Run Code Online (Sandbox Code Playgroud)

  • 我收到了下一个错误:AttributeError:找不到函数'add' (5认同)
  • 请参阅重要说明:http://stackoverflow.com/questions/34417972/no-functions-in-c-sharp-dll-with-rgiesecke-dllexport (4认同)
  • 如果您在 Python 中看到错误 `AttributeError: function 'add' not found`,那是因为它不适用于 `Any CPU`。要修复,请将构建类型设置为 `x32` 或 `x64`(取决于您的 Python 版本)。然后指向右侧的`.dll`,例如在`x64\Release` 文件夹中。 (2认同)

Mic*_*ker 17

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

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

p = PlotData()
p.Start()
Run Code Online (Sandbox Code Playgroud)

  • 完全相同的代码适用于.Net的Python的最新版本.很高兴知道两种解决方案(IronPython和CPython + PythonNet)的工作方式相同. (4认同)

Nic*_*erb 11

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

从网站:

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

除了通常的应用程序库和GAC之外,Python for .NET使用PYTHONPATH(sys.path)来查找要加载的程序集.要确保可以隐式导入程序集,请将包含程序集的目录放在sys.path中.

此程序包仍然要求您的计算机上有本地CPython运行时.有关详细信息,请参阅完整自述文件http://pythonnet.github.io/readme.html


小智 7

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

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

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

无限制地访问所有C#类,具有输出和ref参数的方法,泛型类和泛型方法,扩展方法,私有成员.

重载的装配加载器具有用于搜索装配的定制机制.

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

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

我在等待反馈:)