我最近发现这不适用于我计划编译的全局CUDA C ++代码,后来在Matlab中调用:
int M = 10; float V [M]; 或者如果我要从matlab主机代码中导入M值。
但这有效: 浮动V [10];
我被告知存在一个名为new的函数,我可以使用它来避免这个问题,但是我在线阅读并且仍然很困惑如何使用这个新函数,它似乎只适用于主机代码,是正确的?如果是这样,那么它将不适用于我的情况,因为我的主机代码是在matlab中。这是解决这个问题的一种方法,这样我就不必一个一个地改变矢量长度吗?谢谢!
答案 0 :(得分:1)
我对MATLAB或CUDA一无所知,但你的问题在于C ++。声明的数组必须在编译时固定大小。
声明您的变量M const
。这些是等价的:
int const M = 10;
const int M = 10;
编译器会知道无论你如何运行程序,它都可以假设这些变量总是具有相同的值。
使用new
和delete
进行动态分配。在内存的抽象部分上分配的数组称为“免费存储”(而不是“堆栈”,就像您拥有的那些数组一样)可以动态确定它们的大小。你这样使用它:
float * V = new V[M]; //V is a pointer to some freestore memory
//You use it and pass it like you would a normal array:
V[2] = 5.5;
int x = some_func(V);
//But after you're done, you should manually free the memory
delete [] V; //don't forget the [], since you used [] in the allocation
我不建议这样做,因为忘记删除内存的可能性。
vector
在C ++中,内存管理的工作可以隐藏在称为类的结构之后。
#include<vector>
using std::vector;
vector<float> V(M); //V is a vector of floats, with initial size M
//You use it like a normal array
V[2] = 5.5;
//But to pass it as an array, you need to pass a pointer to the first element
int x = some_func(&V[0]); //read as &(V[0]): pass in the address of V[0]
Thrust是基于标准模板库(STL)的CUDA的C ++模板库。 Thrust允许您通过与CUDA C完全互操作的高级接口以最少的编程工作实现高性能并行应用程序。
http://docs.nvidia.com/cuda/thrust/#vectors
如果您使用固定尺寸,我建议使用解决方案1.如果您使用的是在运行时确定的尺寸,我建议使用矢量。
(顺便说一下,当你将一个普通的数组传递给一个函数时,你实际上是将一个指针传递给第一个元素,而不是数组。数组的名称会自动转换为指针类型。)