GithubHelp home page GithubHelp logo

csharp2python's Introduction

Python调用C#的.so文件来实现Python和C#的交互。

方法一:使用PythonNet

Python for .NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and provides a powerful application scripting tool for .NET developers. It allows Python code to interact with the CLR, and may also be used to embed Python into a .NET application.

相较于另一个Python调用C#的包IronPython,PythonNet是以Python为主体去调用的C#接口,而IronPython是.Net为主体,部分功能使用Python。

使用流程

安装PythonNet

  • pip install pythonnet 这里直接使用来pip来进行安装,在使用conda安装的时候提示没有找到安装包

生成类库

  • 参考C#生成dll类库,这里注意在使用VS生成类库的时候,生成的目标平台选择X86或者x64,应用程序的输出类型改为类库。

实际应用

  • C#代码 Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multi
{
    public class Class1
    {
        public void Show(int a,int b)
        {
            Console.WriteLine((Math.Pow(a, b).ToString()));
            Console.Read();
        }
    }
}
  • Python代码 test.py
import clr
clr.AddReference('Multi') #加载的dll文件名称

from Multi import * #导入命名空间

cla=Class1() # 调用dll接口
cla.Show(2,3) # 接口使用

上面的Python代码在运行的时候要求C#的类库生成文件 xxx.dll 和Python文件处于同一个目录,如果需要在其他目录进行调用需要使用Python的 sys 包中 append 函数来添加工作目录。

import system
system.path.append("x://xxxxx//xxx")

Simple Example 文件夹就是上面代码的修改版本,最后附上PythonNet的详细使用说明,参考官方说明

csharp2python's People

Contributors

pchuan98 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.