使用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;
}
感谢您的帮助。
返回类型通过malloc( )是void *,不要投它。 – blueshift 2012-03-30 07:08:51
谢谢您的评论,当然你是正确的。如果我尝试在C++编译器上编译它,它会产生一个错误或警告。这是我在宏里面演员的逻辑。是的,我应该在问题中指出这一点。为此道歉。 – user1166780 2012-03-30 07:38:44