2012-03-30 84 views
-1

使用Microsoft Visual Studio 2010:C編程malloc宏問題

我可以在C中編寫這種類型的宏嗎?我無法讓它自己工作。

#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT)) 

如果我把它寫這樣的,它的工作原理:

#define MEM_ALLOC(type, nElements) (testFloat = (float*)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT)) 

這是我如何使用它:

#define CACHE_ALIGNMENT 16 
#define INDEX 7 
#define MEM_ALLOC(type, nElements) (type = (float*)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT)) 
#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT)) 
#define MEM_DEALLOC_PTR(type) (_aligned_free(type)) 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    float* testFloat; 

    //MEM_ALLOC_C(testFloat, INDEX); // Problem here. 

    MEM_ALLOC(testFloat, INDEX);  // works 

    //testFloat = (float*)_aligned_malloc(INDEX * sizeof(float), CACHE_ALIGNMENT); // works 

    testFloat[0] = (float)12; 

    //MEM_DEALLOC_PTR(testFloat);  // If we call de-alloc before printing, the value is not 12. 
            // De-alloc seems to work? 

    printf("Value at [%d] = %f \n", 0, testFloat[0]); 

    getchar(); 

    MEM_DEALLOC_PTR(testFloat); 

return 0; 
} 

感謝您的幫助。

+1

返回類型通過malloc( )是void *,不要投它。 – blueshift 2012-03-30 07:08:51

+0

謝謝您的評論,當然你是正確的。如果我嘗試在C++編譯器上編譯它,它會產生一個錯誤或警告。這是我在宏裏面演員的邏輯。是的,我應該在問題中指出這一點。爲此道歉。 – user1166780 2012-03-30 07:38:44

回答

2

想想replacment:

type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT)

成爲

testFloat = (testFloat*)_aligned_malloc(INDEX * sizeof(testFloat), CACHE_ALIGNMENT)

有沒有這樣的事情testFloat*

在純C中,不需要施放malloc的結果。因此,您可以這樣做:

#define MEM_ALLOC_C(var, nElements) (var = _aligned_malloc(nElements * sizeof(*var), CACHE_ALIGNMENT))

+0

你是對的,但Michael Burr關於左值和類型的解釋是我正在尋找的。謝謝你的幫助。 – user1166780 2012-03-30 07:15:45

+0

@ user1166780然而,我提供的解決方案優於其他建議的解決方案,因爲它需要的參數較少且結果相同。 – chacham15 2012-03-30 07:17:12

+0

我現在看到了,謝謝你的解釋。 – user1166780 2012-03-30 07:19:47

1

您的MEM_ALLOC_C()宏中的問題是,您將type參數用作類型和左值。不能正常工作:

#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT)) 
//         ^^^^ ^^^^          ^^^^ 
//         lvalue type          type 

注意如何在你的工作版本,你必須使用一個變量名,其中左值去和其他的斑點類型。

如果你真的想有這樣一個宏,爲什麼不使用它像一個功能,並把結果賦給一個指針,而不是躲在宏內部分配的:

#define MEM_ALLOC_C(type, nElements) ((type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT)) 

testFloat = MEM_ALLOC_C(float, INDEX); 
+0

當然,是的,如此簡單,類型和左值之間的解釋正是我所需要的。現在把它寫成MEM_ALLOC_C(testFloat,float,INDEX); – user1166780 2012-03-30 07:12:27

+0

是的,你可以做到這一點。但是我寧願把這個任務留在宏之外,因爲我認爲這會讓它更明顯地發生什麼,並且它沒有任何價值將它放在宏中(它甚至不會節省任何輸入,除非可能有一兩個空格) 。 – 2012-03-30 07:30:26

+0

給您的額外評論:我不確定是否需要隱藏它。如何編譯
#define MEM_ALLOC_C(var,type,nElements)(var =(type *)_ aligned_malloc(nElements * sizeof(type),CACHE_ALIGNMENT))
不會在C++上產生編譯器警告,其他人會這樣做(因爲它們不要沒有演員陣容),當然我可以在外面寫劇集,但我不確定哪個更好。 – user1166780 2012-03-30 07:35:14