You need to enable JavaScript to run this app. C++与C#跨进程命名管道通信的类对象跨语言序列化实现
优惠活动
大模型
产品
解决方案
定价
更多

C++与C#跨进程命名管道通信的类对象跨语言序列化实现

跨语言自定义对象命名管道传输实现方案

核心前提:C与C#的类内存布局完全不兼容,禁止直接将C类的内存块拷贝到管道传输(C++类中的std::string为带指针的动态结构,跨进程访问会直接触发内存访问违规)。我们采用双方对齐的自定义二进制帧协议实现双向传输,完全不需要依赖第三方库,可直接编译运行。

第一步:定义跨语言统一的传输帧格式(双向通用)

为了兼容C++和C#的原生序列化逻辑(Windows x86/x64平台默认小端序),固定帧结构如下,不依赖任何语言的原生序列化行为:

  • 第1个字节:枚举值(对应CInformation的类型:0=TITLE, 1=STATUS, 2=DEBUG, 3=INFO, 4=OTHER)
  • 接下来4个字节(小端序):UTF-8编码的文本内容的字节长度
  • 后续N个字节:UTF-8编码的文本实际内容

该格式天然解决管道传输的粘包/拆包问题,收发双方可按字段顺序依次读取,无需额外的分隔符处理
注:上述代码仅为示例角色分配,实际部署时可任意指定管道服务端/客户端的角色,只要双方遵循相同的帧格式,双向传输逻辑完全通用

第二步:C++侧实现(序列化/反序列化 + 命名管道收发)

首先对齐原类的逻辑,实现序列化/反序列化工具函数:

#include <windows.h>
#include <vector>
#include <string>
#include <stdexcept>
#include <winnls.h> // 用于字符串编码转换

// 与定义完全对齐的枚举
enum information {
    TITLE,
    STATUS,
    DEBUG,
    INFO,
    OTHER
};

class CInformation
{
private:
    information _info;
    std::string _text; // 统一存储UTF-8编码的字符串,避免跨语言乱码
public:
    void setInformation(information info, std::string text) { 
        _info = info; 
        // 若项目已全局采用UTF-8编码,可直接赋值,无需以下转码逻辑
        int len = MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, NULL, 0);
        std::wstring wtext(len, 0);
        MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, &wtext[0], len);
        len = WideCharToMultiByte(CP_UTF8, 0, wtext.c_str(), -1, NULL, 0, NULL, NULL);
        _text.resize(len-1);
        WideCharToMultiByte(CP_UTF8, 0, wtext.c_str(), -1, &_text[0], len, NULL, NULL);
    }
    inline information GetInfo() { return _info; }
    inline std::string GetText() { return _text; }

    // 序列化为管道可传输的字节流
    std::vector<uint8_t> Serialize() {
        std::vector<uint8_t> buffer;
        // 写1字节枚举值
        buffer.push_back(static_cast<uint8_t>(_info));
        // 写4字节小端序的字符串长度
        uint32_t textLen = static_cast<uint32_t>(_text.size());
        buffer.insert(buffer.end(), {
            static_cast<uint8_t>(textLen & 0xFF),
            static_cast<uint8_t>((textLen >> 8) & 0xFF),
            static_cast<uint8_t>((textLen >> 16) & 0xFF),
            static_cast<uint8_t>((textLen >> 24) & 0xFF)
        });
        // 写UTF-8字符串内容
        buffer.insert(buffer.end(), _text.begin(), _text.end());
        return buffer;
    }

    // 从字节流反序列化为对象
    static CInformation Deserialize(const std::vector<uint8_t>& buffer) {
        if (buffer.size() < 5) {
            throw std::runtime_error("Invalid frame length");
        }
        CInformation info;
        info._info = static_cast<information>(buffer[0]);
        uint32_t textLen = buffer[1] | 
                            (buffer[2] << 8) | 
                            (buffer[3] << 16) | 
                            (buffer[4] << 24);
        if (buffer.size() != 5 + textLen) {
            throw std::runtime_error("Frame length mismatch");
        }
        info._text.assign(buffer.begin() + 5, buffer.end());
        return info;
    }
};

// 简单的命名管道服务端双向收发示例(C++侧作为服务端)
void RunPipeServer() {
    HANDLE hPipe = CreateNamedPipeA("\\\\.\\pipe\\CrossPipe", 
        PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 
        1, 4096, 4096, 0, NULL);
    ConnectNamedPipe(hPipe, NULL);

    // 发送对象示例
    CInformation sendObj;
    sendObj.setInformation(INFO, "这是C++发送的测试内容");
    auto sendBuf = sendObj.Serialize();
    DWORD written;
    WriteFile(hPipe, sendBuf.data(), sendBuf.size(), &written, NULL);

    // 接收对象示例
    uint8_t header[5];
    DWORD read;
    ReadFile(hPipe, header, 5, &read, NULL);
    uint32_t textLen = header[1] | (header[2]<<8) | (header[3]<<16) | (header[4]<<24);
    std::vector<uint8_t> recvBuf(textLen);
    ReadFile(hPipe, recvBuf.data(), textLen, &read, NULL);
    recvBuf.insert(recvBuf.begin(), header, header+5);
    CInformation recvObj = CInformation::Deserialize(recvBuf);
    CloseHandle(hPipe);
}

第三步:C#侧实现(序列化/反序列化 + 命名管道收发)

C#侧完全按照同样的帧格式实现,保证字节级兼容:

using System;
using System.IO;
using System.IO.Pipes;
using System.Text;

// 枚举值与C++侧完全对齐
public enum InformationType
{
    TITLE,
    STATUS,
    DEBUG,
    INFO,
    OTHER
}

public class CInformation
{
    public InformationType InfoType { get; set; }
    public string Text { get; set; }

    // 序列化为字节流,与C++侧格式完全一致
    public byte[] Serialize()
    {
        using var ms = new MemoryStream();
        using var writer = new BinaryWriter(ms, Encoding.UTF8);
        // 写1字节枚举
        writer.Write((byte)InfoType);
        // 写4字节小端序的UTF8字符串长度
        var utf8Bytes = Encoding.UTF8.GetBytes(Text ?? "");
        writer.Write(utf8Bytes.Length);
        // 写UTF8字符串内容
        writer.Write(utf8Bytes);
        return ms.ToArray();
    }

    // 从字节流反序列化
    public static CInformation Deserialize(byte[] buffer)
    {
        using var ms = new MemoryStream(buffer);
        using var reader = new BinaryReader(ms, Encoding.UTF8);
        var infoType = (InformationType)reader.ReadByte();
        var textLen = reader.ReadInt32(); // BinaryReader默认按小端序读取数值
        var textBytes = reader.ReadBytes(textLen);
        return new CInformation
        {
            InfoType = infoType,
            Text = Encoding.UTF8.GetString(textBytes)
        };
    }
}

// 简单的命名管道客户端双向收发示例(C#侧作为客户端)
void RunPipeClient()
{
    using var pipeClient = new NamedPipeClientStream(".", "CrossPipe", PipeDirection.InOut);
    pipeClient.Connect();

    // 接收C++发送的对象
    var headerBuf = new byte[5];
    pipeClient.Read(headerBuf, 0, 5);
    int textLen = BitConverter.ToInt32(headerBuf, 1); // Windows平台为小端序,可直接转换
    var recvBuf = new byte[5 + textLen];
    Buffer.BlockCopy(headerBuf, 0, recvBuf, 0, 5);
    pipeClient.Read(recvBuf, 5, textLen);
    CInformation recvObj = CInformation.Deserialize(recvBuf);

    // 向C++发送对象
    var sendObj = new CInformation
    {
        InfoType = InformationType.STATUS,
        Text = "这是C#发送的测试内容"
    };
    var sendBuf = sendObj.Serialize();
    pipeClient.Write(sendBuf, 0, sendBuf.Length);
}

常见踩坑提醒

  • 严禁直接将C类的内存块通过memcpy拷贝到管道发送:C类中的std::string是带堆指针的结构,跨进程直接读取会触发内存访问违规,完全无法获取实际内容
  • 字符串必须统一使用UTF-8编码,禁止使用C++默认的本地多字节编码、C#默认的Unicode编码,否则跨进程传输中文会出现乱码
  • 所有数值类型统一使用小端序,Windows平台下C++手动实现的字节拼接、C#的BinaryReader/BinaryWriter默认行为完全匹配,无需额外做字节序转换
  • 必须基于帧头的长度字段处理粘包/拆包问题,不要依赖固定长度的缓冲区或者换行符做帧分隔,否则传输结构化数据时会出现帧错乱

其他适配该场景的可行技术方案

  • 轻量结构化序列化:使用Protocol Buffers生成C++、C#两边的对应代码,自动完成跨语言序列化,不需要手动维护帧格式,适合后续类结构持续迭代的场景
  • 文本序列化:C++端引入轻量JSON库、C#端使用原生System.Text.Json将对象转为JSON字符串通过管道传输,调试时可以直接打印管道内容定位问题,适合对性能要求不高的场景
  • 高性能IPC:如果传输频率较高、延迟要求低,可以改用共享内存+互斥锁的通信机制,比命名管道的延迟低一个数量级,但需要自行实现跨进程同步逻辑,开发复杂度更高

内容的提问来源于stack exchange,提问作者NIKHIL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 22:15:03