Python调用一个C#库 [英] Calling a C# library from python

查看:595
本文介绍了Python调用一个C#库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以分享如何从蟒蛇code调用一个简单的C#库(实际上它的WPF)工作的例子? (我一直在使用IronPython的尝试和有太多的麻烦,不支持CPython的图书馆我的Python code使用,所以我想到了周围试图其他方式和Python调用我的C#code)。

Anyone can share a working example on how to call a simple C# library (actually its WPF) from python code? (I have tried using IronPython and had too much trouble with unsupported CPython library my python code is using so I thought of trying the other way around and calling my C# code from Python).

下面是我用打例如:

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的窗户,绘制椭圆

Plotter is a WPF windows that plots an Ellipse

我不知道如何从我的蟒蛇都称呼这种code。有什么建议么?

I don't know how to call this code from my python all. Any suggestions?

推荐答案

它实际上是pretty容易。只要使用的NuGet的UnmanagedExports包添加到您的.NET项目。见<一href=\"https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports\">https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports了解详情。

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.

您可以然后直接出口,而不必做一个COM层。下面是示例C#code:

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

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

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

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

这篇关于Python调用一个C#库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆