2012-07-08 54 views
1

我对D2编程语言相当陌生。我需要实现四边形数据结构。这是用于有效图嵌入及其对偶的邻接数据结构。 从以C以往的经验,我开始用下面的实现: 高效四边形实现的自定义对齐选项

struct edge(T) { 
    edge* next; 
    T* data; 
    uint position; 
} 
alias edge[4] qedge; 
edge* new_edge() { 
    qedge* q = new qedge; // does not compile, just analogous 
    // initialize the four edges (q[i].position = i) 
    return cast (edge*) q; 
} 

这工作正常,但这个位置字段缠着我 - 它只是浪费空间存在。 当为qedge数组分配内存时,是否有办法对齐(8 * $ {机器字大小})边界(然后我不需要额外的位置字段,因为边缘在哪个位置的信息位于qedge数组将被编码到边缘地址中)?

我的目标是实现一个高效可爱的实现(这就是为什么我选择了D),因此欢迎任何其他建议。

编辑:这里是一段代码,使事情更加清晰http://dpaste.dzfl.pl/e26baaad

module qedge; 

class edge(T) { 
    edge next; 
    T* data; 
} 

alias edge!int iedge; 
alias iedge[4] qedge; 

import std.stdio; 
import std.c.stdlib; 

void main() { 
    writeln(iedge.sizeof); // 8 
    writeln(qedge.sizeof); // 32 
    // need something for the next line, 
    // which always returns an address, divisible by 32 
    qedge* q = cast (qedge*) malloc(qedge.sizeof); 
    writeln(q); // ex. 0x10429A0 = 17050016, which is, does not start at 32-byte boundary 
} 
+0

既然你改变边缘的一类 - 使用'new'操作。我仍然对你想要做的事感到困惑......也许一个简单的C或C++代码会使它更加清晰! :)或者,只需来IRC(服务器:irc.oftc.net,频道:#D),这样我们就可以聊天了。 – DejanLekic 2012-07-08 15:07:45

回答

1

直接回答这个问题 - 使用align(N)指定要对齐。但请记住这一点(引自dlang.org):Do not align references or pointers that were allocated using NewExpression on boundaries that are not a multiple of size_t

参考手册http://dlang.org有一个关于比对的部分 - http://dlang.org/attribute.html#align

说,T是int - 边缘!int在64位体系结构上已经是24个字节大了。 D与C对齐并没有太大的不同。检查以下内容(可运行/编辑在代码:http://dpaste.dzfl.pl/de0121e1),无需`的malloc()`

module so_0001; 
// http://stackoverflow.com/questions/11383240/custom-alignment-options-for-an-efficient-quad-edge-implementation 

struct edge(T) { 
    edge* next; 
    T* data; 
    uint position; 
} 
alias edge!int iedge; 
alias edge!int[4] qedge; 

/* not a good idea for struct... it is a value type... 
edge!int new_edge() { 
    // in the original example it used new... D is not C++ to mix value and reference types! :) 
} 
*/ 

import std.stdio; 

int main() { 
    writeln(iedge.sizeof); 

    //         64bit 
    //        ---------- 
    writeln(iedge.next.offsetof);  // 0 
    writeln(iedge.data.offsetof);  // 8 
    writeln(iedge.position.offsetof); // 16 
    writeln(qedge.sizeof); 
    return 0; 
}