2017-04-07 40 views
0

我無法找到如何製作C風格的聯盟。在documentation中給出的示例中:如何製作C風格的聯盟

(define a-union-type 
(_union (_list-struct _int _int) 
     (_list-struct _double _double))) 
(define a-union-val 
    (cast (list 3.14 2.71) 
      (_list-struct _double _double) 
      a-union-type)) 

所有的作品。但是,如果是投改爲_INT:

(define a-union-val 
    (cast (list 3 2) 
      (_list-struct _int _int) 
      a-union-type)) 

我獲得以下錯誤:

cast: representation sizes of from and to types differ 
    size of from type: 8 
    size of to size: 16 

這在某種程度上是有道理的,但問題是,如何建立這個聯盟?

你能解釋一下make-union-type和_union之間的區別嗎?由於我不清楚從文檔。

非常感謝。

+0

3.14和2.71不是'int's –

+0

是的,但這裏不是問題...編輯。 – Ondrej

回答

1

僅當(ctype-sizeof from-type)等於(ctype-sizeof to-type)時投射纔有效,因此只允許使用最大的聯合變體。嘗試使用手動分配和union-set!代替:

(define a-union-val (ptr-ref (malloc a-union-type) a-union-type)) 
(union-set! a-union-val 0 (list 3 2)) 

union-set!第二個參數是你想要的變型的指數。

+0

我是否需要手動釋放該內存? – Ondrej

+1

@Ondrej這裏寫的不是使用malloc。但取決於你在做什麼,你可能需要使用不同的malloc模式,對於某些模式,答案是肯定的。請查閱malloc文檔,並使用'cpointer-gcable?'來查明內存是否爲GCd,例如'(cpointer-gcable?(union-ptr a-union-val))'。 –