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类函数调用
            }


     

  • 相关阅读:
    Ping
    boost::python开发环境搭建
    mingw和libcurl
    ssh远程执行命令使用明文密码
    netty源码阅读之UnpooledByteBufAllocator
    Direct ByteBuffer学习
    clions的使用
    netty中的PlatformDependent
    STL之priority_queue(优先队列)
    c++线程调用python
  • 原文地址:https://www.cnblogs.com/jinyu20180311/p/10501749.html
Copyright © 2011-2022 走看看