---
title: "关于c/c++中缓冲的使用"
author: "linshenqi"
date: "2010-03-26T10:48:26Z"
tags: []
categories: ["编程语言"]
slug: "c-c"
draft: false
lastmod: "2010-03-26T10:48:26Z"
id: 625307
url: "https://linshenqi.iteye.com/blog/625307"
---

c/c++中使用缓冲可以提高系统效率，避免在数据交互时出现死锁等问题。尤其是在网络编程中，当协议结构比较复杂，牵扯到的数据结构比较多的时候，用缓冲可以提高程序运行效率。尤其是结构体，一般的处理方法就是针对不同的结构体编写不同的处理函数。不过在c语言中不支持oo的情况下，实现不了多态，难免降低效率。这时可以把相应的结构体转化为缓冲字节流，然后根据结构体（协议）定义做相应的处理，等于是变相的在c语言中实现了多态。

一个例子：

```c++

 unsigned char *buf;
	tagText *text = (tagText *)malloc(sizeof(tagText));
	memset(text, 0, sizeof(tagText));
	strcpy(text->str, "wefwfw");
	text->x = 23;
	text->y = 30;
	buf = (unsigned char *)text;
	tagText *t = (tagText *)buf;
	printf("%s\n", t->str);
	printf("%d\n", t->x);
	printf("%d\n", t->y);

```