[英]How do I copy a C-style array into a void pointer in C++?
So basically I've recently started coding in C++ instead of C so maybe that's not the C++ way of doing this, but I've got a program where the user passes an array as a function parameter ( void foo(void* pass_array_here)
) and I want to copy it in a private member of a class, also declared as void* array_private
.所以基本上我最近开始编码 C++ 而不是 C 所以也许这不是 C++ 这样做的方式,但我有一个程序,用户将数组作为 function 参数传递(
void foo(void* pass_array_here)
)我想将它复制到 class 的私有成员中,也声明为void* array_private
。 I'm copying it like this:我是这样复制的:
void foo(void* pass_array_here) {
array_private = pass_array_here;
}
I must note that I'm working with OpenGL so I don't know if I can rely on the new
keyword or the heap in general.我必须注意,我正在使用 OpenGL,所以我不知道我是否可以依赖
new
关键字或一般的堆。 So how do I do that?那我该怎么做呢?
(Note, on a sizeof
call, a 9-element float array appeared as 8 bytes in the stack, so it definitely didn't work). (请注意,在
sizeof
调用中,一个 9 元素浮点数组在堆栈中显示为 8 个字节,因此它肯定不起作用)。
void*
is not very useful.void*
不是很有用。std::array
for a fixed size array, or std::vector
for dynamic size array.std::array
作为固定大小的数组,或者使用std::vector
作为动态大小的数组。array_private = pass_array_here
is simply assigning the pointer, not copying the array content.array_private = pass_array_here
只是简单地分配指针,而不是复制数组内容。std::array
or std::vector
as suggested in point 2 above, you can utilize the copy constructor of these classes to actually copy the array's content easily:std::array
或std::vector
,则可以利用这些类的复制构造函数轻松地实际复制数组的内容: void foo(std::vector<SomeType> const & pass_array_here) {
array_private = pass_array_here;
}
foo
does not need to use the array after calling the function, you can save the copy of the data, and utilize C++ move semantics (available since C++ 11):foo
的调用者在调用 function 后不需要使用数组,您可以保存数据副本,并利用 C++ 移动语义(自 C++ 11 起可用): void foo(std::vector<SomeType> && pass_array_here) {
array_private = std::move(pass_array_here);
}
std::vector
but an old C style array, it is possible to initialize the std::vector
member from it (which will copy the data).std::vector
而是一个旧的 C 样式数组,则可以从中初始化std::vector
成员(这将复制数据)。 See: std::vector::assign . For 4, 5 and 6 above, your private data member will have to be defined as:对于上面的 4、5 和 6,您的私有数据成员必须定义为:
std::vector<SomeType> array_private;
If you need to access the data buffer managed by an std::vector
, you can use std::vector::data
: std::vector::data .如果您需要访问由
std::vector
管理的数据缓冲区,您可以使用std::vector::data
: std::vector::data 。 You can cast this data pointer into a void*
if you need to pass it to a C style function, eg in opengl (no need to copy the data).如果需要将其传递给 C 样式 function,例如在 opengl 中(无需复制数据),您可以将此数据指针转换为
void*
。
More about move semantics and R value references here: Understanding rvalue references有关移动语义和 R 值引用的更多信息,请参见: 了解右值引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.