Python C# 通信2种路子

文章目录

  • Pythonet
    • 确保安装的是Python3.7
    • 下载最新C#
    • 下载的Pythonet 插件
    • 环境变量名
    • 模拟算法的Python 内容
    • 处理自己的Python Package
    • C# 里 Pythonnet 内容
    • C# 运行结果
  • Socket (TCP)

Pythonet

确保安装的是Python3.7

我是用的Anaconda的。确保Python3.7更新过:

pip install update

如果出现“permission denied”的错误,Windows用户可以使用以下解决:链接

下载最新C#

当前我用的是Microsoft Visual Studio Community 2019,版本 16.11.8。里面配备的.NET为4.8.04084 版本。

下载的Pythonet 插件

项目 > 管理NuGet程序包(N) > Pythonet.runtime.standard for python37
Python C# 通信2种路子_第1张图片

环境变量名

Python C# 通信2种路子_第2张图片
在Unity 项目内添加以下环境变量:
变量名称:PYTHONNET_PYDLL

变量名称:PYTHONHOME

变量名称:PYTHONPATH

模拟算法的Python 内容

因为要放进module里,所以python 算法的引用部分要稍微严格一些,否则会容易找不到路径。从蓝色部分开始为外文件夹里面有三个内容:

  1. MyTool (主要的算法内容)
  2. MyTool.egg-info
  3. setup.py

Python C# 通信2种路子_第3张图片

main.py

from .toollib import tool
def main_method():
    print("Hi")
    mytool = tool.Tool()
    mytool.makeTool()

tool.py

class Tool():
    def __init__(self):
        tool_name = "my toollib"

    def makeTool(self):
        print("Making toollib...")

init.py

用空的就行

处理自己的Python Package

setup.py
可自定义,这个文件要放在主要文件夹的外面。

from setuptools import setup, find_packages
setup(
    name = 'MyTool',
    version = '0.1.0',
    packages = find_packages(),
    install_requires = ['Cython',
                        'matplotlib>=3.2.2',
                        'numpy>=1.18.5',
                        'opencv-python>=4.1.2',
                        'Pillow',
                        'PyYAML>=5.3',
                        'scipy>=1.4.1',
                        'torch>=1.7.0',
                        'torchvision>=0.8.1',
                        'tqdm>=4.41.0',
                        'seaborn>=0.11.0',
                        'pandas'],
    )

完成以上内容,开始将你的算法内容打包进你的pip list. run 以下内容的路径与setup.py的要在同一目录下。

cd MyToolPk
pip install -e .

安装后,用pip list检查

Python C# 通信2种路子_第4张图片

C# 里 Pythonnet 内容

using System;
using Python.Runtime;
using System.Collections.Generic;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            string xx = "3 4";
            string[] res = xx.Split(" ");
            int[] ans = new int[2];
            for (int i = 0; i < xx.Length - 1; i++)
            {
                ans[i] = Int16.Parse(res[i]);
                Console.WriteLine(ans[i]);
            }
            using (Py.GIL())
            {
                dynamic toollib = Py.Import("MyTool.main");
                dynamic toolmethod = toollib.main_method();
                Console.WriteLine(toolmethod);
                Console.ReadKey();
            }
        }
    }
}

C# 运行结果

Python C# 通信2种路子_第5张图片
console 那个问题暂时就不解决了,如果有同志知道怎么解决欢迎留言学习。好啦,主要就是验证下Pythonet是否可用和到底怎么用。

Socket (TCP)

这个版本会比上面的简单,以及速度快。

import cv2
import socket
host, port = "127.0.0.1", 1234
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))

cv2.namedWindow("frame")

with open("gt.txt", encoding='utf-8') as f:
    coords = ""
    ct = 0
    for line in f:
        tmp_items = line.split(',')
        coords += " ".join(tmp_items[5:7])+" "
        if tmp_items[1] == '5':
            ct+=1
            print(ct)
            result = coords.strip()
            sock.sendall(result.encode("UTF-8"))
            receivedData = sock.recv(1024).decode("UTF-8")
            f = cv2.imread(r"ZebraFish-04/imgT/" + tmp_items[0].zfill(6)+".jpg")
            result_cc = list(map(int,result.split(" ")))
            cv2.circle(f, (result_cc[0],result_cc[1]),10, (255, 255, 0),-1)
            cv2.circle(f, (result_cc[2],result_cc[3]),10, (255, 255, 0),-1)
            f = cv2.resize(f,(960, 480))
            cv2.imshow("frame", f)
            cv2.waitKey(1)
            # print(coords)
            # time.sleep(1)
            coords = ""
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using System.Threading;
using System.Collections;

public class connect2 : MonoBehaviour
{
    Thread mThread;
    public string connectionIP = "127.0.0.1";
    public int connectionPort = 1234;
    IPAddress localAdd;
    TcpListener listener;
    TcpClient client;

    Vector3 receivedPos = Vector3.zero;

    public GameObject fish1;
    public GameObject fish2;
    Vector3 fish1_go = new Vector3();
    Vector3 fish2_go = new Vector3();
    int[] ans;
    string[] res = new string[] { "1", "1" };
    public List<GameObject> fishes;
    public Queue msgq = new Queue();
    bool running;
    private void Update()
    {
        List<Vector3> coords = new List<Vector3>();
        if (msgq.Count > 0)
        {
            //Debug.Log(_helloRequester.msgq.Dequeue().ToString() + "   left:"+ _helloRequester.msgq.Count);
            res = (msgq.Dequeue()).ToString().Split(',');
            for (int i = 0; 2 * i < 2; i++)
            {
                Debug.Log("->>>>>" + (float.Parse(res[2 * i]) / 1400f) + ":----" + (-float.Parse(res[2 * i + 1]) / 1400f) + ":----" + 0f);
                fishes[i].transform.localPosition = new Vector3(((float.Parse(res[2 * i])) / 1280f)-0.5f, (-float.Parse(res[2 * i + 1]) / 960f) + 0.7f, 0f);   //X:2704   Y:1520
                Debug.Log("Q.length:" + msgq.Count);
            }
        }
        else{Debug.Log("null");}
    }

    private void Start()
    {
        fish1 = GameObject.Find("fish1");
        fish2 = GameObject.Find("fish2");
        //fish3 = GameObject.Find("fish3");
        fish1_go = new Vector3(0f, 0f, 1f);
        fish2_go = new Vector3(0f, 0f, 1f);
        fishes = new List<GameObject> { fish1, fish2 };
        //fish3_go = new Vector3(0f, 0f, 1f);
        ans = new int[] { 0, 0 };
        ThreadStart ts = new ThreadStart(GetInfo);
        mThread = new Thread(ts);
        mThread.Start();
    }

    void GetInfo()
    {
        localAdd = IPAddress.Parse(connectionIP);
        listener = new TcpListener(IPAddress.Any, connectionPort);
        listener.Start();

        client = listener.AcceptTcpClient();

        running = true;
        while (running)
        {
            SendAndReceiveData();
        }
        listener.Stop();
    }

    void SendAndReceiveData()
    {
        NetworkStream nwStream = client.GetStream();
        byte[] buffer = new byte[client.ReceiveBufferSize];

        //---receiving Data from the Host----
        int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); //Getting data in Bytes from Python
        string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead); //Converting byte data to string
        
        if (dataReceived != null)
        {
           Debug.Log(dataReceived);
           msgq.Enqueue(dataReceived);
            //---Sending Data to Host----
            byte[] myWriteBuffer = Encoding.ASCII.GetBytes("LALALAL"); //Converting string to byte data
            nwStream.Write(myWriteBuffer, 0, myWriteBuffer.Length); //Sending the data in Bytes to Python
        }
    }

    public static Vector3 StringToVector3(string sVector)
    {
        // Remove the parentheses
        if (sVector.StartsWith("(") && sVector.EndsWith(")"))
        {
            sVector = sVector.Substring(1, sVector.Length - 2);
        }

        // split the items
        string[] sArray = sVector.Split(',');
        // store as a Vector3
        Vector3 result = new Vector3(
            float.Parse(sArray[0]),
            float.Parse(sArray[1]),
            float.Parse(sArray[2]));
        return result;
    }
}

你可能感兴趣的:(Deep,Learning,General,python,c#,开发语言)