假設你有這樣的結構:鑄造指向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)') –