我有这些C宏,并希望将它们转换为纯D(因为与原始C文件接口)。C到D:struct为type并初始化?
#define __KS_TYPE(type_t) \
typedef struct __kstream_t { \
unsigned char *buf; \
int begin, end, is_eof; \
type_t f; \
} kstream_t;
#define __KS_BASIC(type_t, __bufsize) \
static inline kstream_t *ks_init(type_t f) \
{ \
kstream_t *ks = (kstream_t*)calloc(1, sizeof(kstream_t)); \
ks->f = f; \
ks->buf = (unsigned char*)malloc(__bufsize); \
return ks; \
} \
static inline void ks_destroy(kstream_t *ks) \
{ \
if (ks) { \
free(ks->buf); \
free(ks); \
} \
}
这是我目前实施:
import std.stdio;
import core.stdc.config;
import core.stdc.stdlib;
struct __kstream_t(type_t) {
ubyte *buf;
int begin, end, is_eof;
type_t f;
}
mixin template __KS_BASIC(type_t, ubyte __bufsize){
// mixin(__KS_TYPE!type_t);
alias kstream_t = __kstream_t!type_t;
static kstream_t *ks_init(type_t f)
{
kstream_t *ks = cast(kstream_t*)calloc(1, kstream_t.sizeof);
ks.f = f;
ks.buf = cast(ubyte*)malloc(__bufsize);
return ks;
}
static void ks_destroy(kstream_t *ks)
{
if (ks) {
free(ks.buf);
free(ks);
writeln("Destroyed struct.");
}
}
}
void main(){
mixin __KS_BASIC!(int, 12);
auto ks = ks_init(14);
ks.buf[0] = 125;
writeln("ks.f: ", ks.f, ", buf: ", ks.buf[0]);
ks_destroy(ks);
}
的d版本目前运行良好,但我可以做任何调整和代码的微调?它仍然看起来非常C-ISM。例如,kh_init
可以仅仅是这样的:
static kstream_t *ks_init(type_t f){
kstream_t* ks;
ks.f = f;
return ks;
}
不过这个版本给一个sementation fault
。
此外,在D版本中,手动处理内存ks_init
和ks_destroy
是否有任何好处?
这个问题应该被迁移到http://codereview.stackexchange.com –
ks_init()不能像你说的,因为你需要分配你以后在'ks.f = F使用kstream_t对象; '线。你需要调用malloc(),calloc()或OR(D方法),你应该可以简单地做到这一点:'kstream_t * ks = new kstream_t;' – DejanLekic
@RobertH:复活节假期让我暂时离开了。所以这里是我的回应:我现在所使用的'工作'D版本未经测试。我还没有进入优化步骤。我有兴趣有一个工作和真正的D版本。此外,我被告知,SO比其他兄弟姐妹拥有更多的D程序员。所以我想在这里发帖。 – biocyberman