假设你有这样的结构:铸造指向struct的指针与const成员为结构
struct nix_codec {
nix_uint8 state;
nix_uint8 mode;
nix_uint8 flags;
nix_size offset;
nix_uint32 codepage;
nix_utf8 const *const *aliases;
void (*delete)(
struct nix_codec *codec,
struct nix_error *error
);
struct nix_codec* (*clone)(
struct nix_codec const *codec,
nix_int8 mode,
struct nix_error *error
);
nix_size (*decode)(
struct nix_codec *codec,
nix_byte const *bdata,
nix_size bsize,
nix_rune *udata,
nix_size usize,
struct nix_error *error
);
nix_size (*encode)(
struct nix_codec *codec,
nix_rune const *udata,
nix_size usize,
nix_byte *bdata,
nix_size bsize,
struct nix_error *error
);
};
typedef struct {
nix_uint8 const state;
nix_uint8 const mode;
nix_uint8 const flags;
nix_size const offset;
nix_uint32 const codepage;
nix_utf8 const *const *const aliases;
} nix_codec;
人们也有多种功能,其被用于创建nix_codec*
情况下,例如为UTF-8编码解码器它看起来就像这样:
static nix_size self_decode
(
struct nix_codec *codec,
nix_byte const *bdata,
nix_size bsize,
nix_rune *udata,
nix_size usize,
struct nix_error *error
)
{ /* UTF-8 decode function, too long to post here */}
static nix_utf8 const *const aliases[] = {
"UTF-8",
"UTF8",
"CP65001",
NULL,
};
nix_codec *nix_codec_utf8
(
nix_int8 mode,
struct nix_error *error
)
{
struct nix_codec *codec = NULL;
if ((mode != NIX_CODEC_STRICT) && (mode != NIX_CODEC_ESCAPE)
&& (mode != NIX_CODEC_REPLACE) && (mode != NIX_CODEC_IGNORE)) {
return NULL;
}
codec = calloc(1, sizeof(struct nix_codec));
if (codec == NULL) {
return NULL;
}
codec->mode = mode;
codec->codepage = 65001;
codec->aliases = aliases;
codec->decode = &self_decode;
codec->encode = &self_encode;
codec->flags = (NIX_CODEC_COMPATIBLE | NIX_CODEC_MULTIBYTE | NIX_CODEC_ABSOLUTE);
return (nix_codec*)codec;
}
对于传统的单字节编码的功能是基于这样的结构:
struct nix_sbmap {
nix_uint8 byte;
nix_rune rune;
};
struct nix_sbcodec {
struct nix_codec base;
struct nix_sbmap const *entries;
nix_size count;
};
注意struct nix_sbcodec
和struct nix_sbmap
在源文件中的声明,而不是在标题中,因此不需要使用variant
模式。相应的功能,例如nix_codec_koi8r()
,分配struct nix_sbcodec
,设置其base
,entries
和count
成员,然后将其转换为nix_codec
并将其返回。每一个实际encode()
和decode()
呼叫使用这个公共函数执行:
nix_size nix_codec_decode
(
nix_codec *codec,
nix_byte const *bdata,
nix_size bsize,
nix_rune *udata,
nix_size usize,
struct nix_error *error
)
{
nix_size result = 0;
struct nix_codec *self = (struct nix_codec*)codec;
return self->decode(self, bdata, bsize, udata, usize, error);
}
注意state
,mode
,flags
和offset
成员可能是有趣的,使用任何编解码器的人(其中大部分是在编解码器的创造者的功能设置,offset
被调用encode()
和decode()
功能改变后,代表功能退出之前其已成功处理的字节/ Unicode字符数。每个编解码器都有自己的encode()
和decode()
功能,当你看到。
现在的问题是:这个技巧是否正确并保证可以在C标准下工作?
在此先感谢!
什么问题? – IdeaHat
'class'?在'c'中? –
这是C不是C++吧?你为什么做这个?这坦率地说是一个等待发生的事故。如果你将一个'my_object'赋给另一个,你期望编译器做什么? (提示:'memcpy(b,a,sizeof(my_object)') –