c# - 从 python 调用 C# 库

标签 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();
       }
    }
}

Plotter 是一个绘制椭圆的 WPF 窗口

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

最佳答案

其实很简单。只需使用 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)

关于c# - 从 python 调用 C# 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7367976/

相关文章:

C#单元测试数精度题

C# 键盘映射

c# - 如何使用 Reflection.Emit 添加引用

python - 如何使用 SciPy/Numpy 过滤/平滑?

python - 如何根据列数据类型过滤数据框

Erlang 的 C 接口(interface)

.net - native 线程异常崩溃 .Net 应用程序无一异常(exception)

java - 在java中用通用参数覆盖Kotlin方法 - 方法冲突

c# - webapi2 返回不带引号的简单字符串

python - 使用正则表达式搜索文件并返回函数名列表