通过命名管道将指向大型数组的指针从C#传递到Python

时间:2019-03-25 20:12:24

标签: c# python named-pipes

我在C#中有一个大型数组,我希望将其传递给Python进行处理。除了发送数组的值,我想发送一个指针并让Python以这种方式访问​​它。这是我的C#代码:

NamedPipeServerStream server = null;
BinaryReader br = null;
BinaryWriter bw = null;

Thread thread = new Thread(() =>
    {
        server = new NamedPipeServerStream("NPtest");

        Console.WriteLine("Waiting for connection...");
        server.WaitForConnection();

        Console.WriteLine("Connected.");
        br = new BinaryReader(server);
        bw = new BinaryWriter(server);
    })
{ IsBackground = true };
thread.Start();

Process process = new Process() { StartInfo = new ProcessStartInfo("python.exe", "script.py") { UseShellExecute = false } };
process.Start();
Thread.Sleep(1000);

byte[] bytes = new byte[] { 32, 164, 9 };

IntPtr pointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, pointer, bytes.Length);
bw.Write(bytes.Length);
bw.Write(pointer.ToInt64());
Console.ReadKey(true);
Marshal.FreeHGlobal(pointer);

server.Close();
server.Dispose();

这是script.py:

import struct
import ctypes
import numpy

f = open(r'\\.\pipe\NPtest', 'r+b', 0)

length = struct.unpack('i', f.read(4))[0]
f.seek(0)
print(length)
pointer = struct.unpack('q', f.read(8))[0]
f.seek(0)
print(hex(pointer))
data = numpy.ctypeslib.as_array(ctypes.cast(pointer, ctypes.POINTER(ctypes.c_ubyte * length)), shape=(length, ))
print(data)

当我到达Python的倒数第二行时,它崩溃了并且没有错误。我猜想这与Python无法访问该内存有关。有没有办法解决?还是有其他架构可以将大型数组从C#传递给Python,以便可以执行处理?

0 个答案:

没有答案