在 Windows 上的 C++ 中实现强大、简单(且快速)的进程间通信



我正在为两个第三方程序开发一个插件:Windows (7) 上 C++ 中的 A 和 B,并且需要一种健壮、相对简单(且快速)的方式来在两个程序之间进行通信。

通信是单向的:基于程序 A 中的用户交互,我希望程序 A 中的插件发送一个信号,最终调用程序 B 中的插件内的函数。

协议很简单。这是我在 B 中的插件中接收函数的签名:

struct XYZ { 
   double x, y, z;
}
void polyLineSelected(long id, std::vector<XYZ> & points);

您建议如何做到这一点?

到目前为止,在Windows上实现单向通信的最简单方法是发送WM_COPYDATA消息。将任意数据从一个应用程序移动到另一个应用程序需要一个COPYDATASTRUCT参数。

对于您的特定示例,发送方的实现如下所示:

// Declare symbolic constants to identify data
enum DataType {
    DataType_Points
};
// Declare struct to hold compound data
struct IPCData {
    long id;
    XYZ pts[];
};
// Allocate buffer
const size_t bufferSize = offsetof(IPCData, pts[points.size()]);
vector<char> buffer(bufferSize);
IPCData* pData = reinterpret_cast<IPCData*>(&buffer[0]);
// Fill the buffer
pData->id = 42;
copy(points.begin(), points.end(), &pData->pts[0]);
// Prepare COPYDDATASTRUCT
COPYDATASTRUCT cds = { 0 };
cds.dwData = DataType_Points;  // Can be used by the receiver to identify data
cds.cbData = bufferSize;
cds.lpData = pData;
// Send the data
SendMessage(hWndRecv, WM_COPYDATA,
            (WPARAM)hWndSender,
            (LPARAM)(LPVOID)&cds);

最新更新