2012-03-30 90 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