简体   繁体   中英

Copy std::vector to void pointer

I have a std::vector<MyVertex> where MyVertex is a struct. I have to push this data to the vertex buffer in Direct3D 9 and the examples I've seen use a memcpy . Unfortunately, memcpy crashes my application so I'm definitely doing something wrong.

std::vector<MyVertex> m_VertsBuff0;

void* vbPtr;
vertexbuffer->Lock (0, 0, &vbPtr, D3DLOCK_DISCARD);
memcpy (vbPtr, &m_VertsBuff0[0], sizeof(m_VertsBuff0)); // also tried sizeof(MyVertex)*m_VertsBuff0.size()
// std::copy(m_VertsBuff0.begin(), m_VertsBuff0.end(), vbPtr); // gives a compiler error void* unknown size
vertexbuffer->Unlock ();
device->SetStreamSource (0, vertexbuffer, 0, sizeof(m_VertsBuff0[0]));

Update:
This was working before when I just used an array instead of a vector . It didn't seem that I had to initialize the void* in the first place, because the example was working just fine. Then I changed it to a vector and it went wrong. Why is it that I have to initialize the void* all of a sudden and doing so still crashes my application.

memcpy (vbPtr, m_VertsBuff0.data(), sizeof(MyVertex) * m_VertsBuff0.size());

使用m_VertsBuff0.size() * sizeof(MyVertex)代替sizeof(m_VertsBuff0)并确保'vbPtr'指向正确分配的内存,例如:

void* vbPtr = new char[v.size() * sizeof(int)];

You must initialize your vbPtr;

  void* vbPtr = new char[v.size() * sizeof(MyVertex)];
  memcpy (vbPtr, v.data(), v.size() * sizeof(MyVertex));

嗯,我认为您必须在调用map之前将vbPtr初始化为NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM