zoukankan      html  css  js  c++  java
  • c#(IronPython)调用Python方法

    直接一段代码演示

     public void StartTCP()
            {
                ScriptEngine engine = Python.CreateEngine();
                var paths = engine.GetSearchPaths();
                List<string> lstPath = new List<string>();
                lstPath.AddRange(paths);
                lstPath.Add("Script");
               // lstPath.Add(@"D:Program FilesPythonPython37Lib");
                lstPath.Add(@"D:Program FilesIronPython 2.7Lib");
                engine.SetSearchPaths(lstPath.ToArray());
                var scope = engine.CreateScope();
                var source = engine.CreateScriptSourceFromFile("Script/TCPClsClient.py");
                 dynamic result= source.Execute(scope);
                //调用函数的2种方法
                // 第一种,通过参数方式转换委托调用,看起来不太简洁
                var  SetAddress = scope.GetVariable<Action<string,int>>("SetAddress");
                var Con = scope.GetVariable<Action>("Connect");
                var SendData = scope.GetVariable<Action<string>>("Send");
                var Revcive = scope.GetVariable<Action>("Revcive");
                var Close = scope.GetVariable<Action>("Close");
                SetAddress("localhost", 7777);
                Con();
                SendData("jinyu");
                Revcive();
                Close();
                //第二种,没有智能化提示,必须要转换为dynamic
                result = scope;
                result.SetAddress(result, "localhost", 7777);
                result.Connect();
                result.Send("jinyu");
                result.Recvice();
                result.Close();
                //因为是2.7版本,所以不能支持3.X版本的类方法调用
                //例如: result= scope.GetVariable("TCPClsClient");//调用构造,返回实例
                //result.SetAddress(result, "localhost", 7777);//不能执行,版本不支持3.X类函数调用
            }


     

  • 相关阅读:
    一步一步写数据结构(线索二叉树)
    Android studio 下JNI编程实例并生成so库
    IOS和Android音频开发总结
    IDEA常用快捷键
    Spring事务简介
    IDEA新建Springboot项目
    140201126杨鹏飞作业六
    140201126杨鹏飞作业三
    140201126杨鹏飞作业七
    自我介绍
  • 原文地址:https://www.cnblogs.com/jinyu20180311/p/10501749.html
Copyright © 2011-2022 走看看