D
D
Dmitry2020-09-23 20:27:18
C++ / C#
Dmitry, 2020-09-23 20:27:18

How to call a python function in a c# program and get its result?

You need to write a program in c # (or at least in c ++) so that you can load a python script, call a function from it, transfer an array (well, or other data) to it, the function worked and returned the result to the main program. The variant with calling the interpreter and passing parameters to it is not suitable. You need speed, as much as possible of course

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
Timur Pokrovsky, 2020-09-23
@Lepeshka

c#

using Process process = Process.Start(new ProcessStartInfo {
  FileName = "python",
  Arguments = @"path\pyscript.py",
  UseShellExecute = false,
  RedirectStandardInput = true,
  RedirectStandardOutput = true
});

int[] arr = { 1, 2, 3, 4, 5, 6 };

using BinaryWriter writer = new BinaryWriter(process.StandardInput.BaseStream);
Array.ForEach(arr, writer.Write);
writer.Flush();

using BinaryReader reader = new BinaryReader(process.StandardOutput.BaseStream);
int result = reader.ReadInt32();

Console.WriteLine(result);

Console.ReadKey(false);

python:
import os
import sys

stdin = sys.stdin.buffer
stdout = sys.stdout.buffer


def get_int_list():
    stdin.seek(0, os.SEEK_END)
    n = stdin.tell() // 4
    arr = [0] * n

    for i in range(n):
        arr[i] = int.from_bytes(stdin.read(4), byteorder='little')

    return arr


def write_int(i: int):
    stdout.write(i.to_bytes(4, byteorder='little'))


nums = get_int_list()

result = sum(nums)

write_int(result)

Result: 21

S
shurshur, 2020-09-24
@shurshur

You can look towards IronPython. Here is an example: https://www.red-gate.com/simple-talk/dotnet/net-fr...

V
Vasily Bannikov, 2020-09-24
@vabka

If you need speed, as much as possible, then one of the options is to implement this algorithm in C # or C ++.
As a last resort, connect python as a library and work with it: https://habr.com/en/post/168083/

R
Roman Mirilaczvili, 2020-09-24
@2ord

Calling an interpreter is rather slow. Instead of this method, it makes sense to use Python.NET
Or the method from the documentation
https://docs.python.org/3/extending/embedding.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question