c++/CLR Direct3D

Started by
3 comments, last by Promit 16 years, 8 months ago
I am trying to initialize Direct3D 9 in a C++/CLR application. However, the create device function gives me a compilation error: error C2664: 'IDirect3D9::CreateDevice' : cannot convert parameter 6 from 'cli::interior_ptr<Type>' to 'IDirect3DDevice9 **' 1> with 1> [ 1> Type=IDirect3DDevice9 * 1> ] 1> Cannot convert a managed type to an unmanaged type The code giving the error: HRESULT hr; hr = pd3dObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, pd3dPP, &pd3dDevice); I thought a managed C++ class can have pointers to unmanaged code?
-----Quat
Advertisement
After more experimenting, I found that this works:

pin_ptr<IDirect3DDevice9*> p = &pd3dDevice

HRESULT hr;
hr = pd3dObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
(HWND)hwnd.ToPointer(),
D3DCREATE_SOFTWARE_VERTEXPROCESSING, pd3dPP, p);

Why though? Isn't pd3dDevice (which is a data member of a ref class)
unmanaged since I'm using * syntax? I don't see why I have to pin
down an unmanaged pointer...
-----Quat
You're better off declaring the pointer as a local on the stack, creating it into that, and then assigning it into the member. This is what SlimDX does for most of its creation functions.

The reason is that, if I have this right, pd3ddevice is a member of a ref class. That means that the pointer itself is on the managed heap, and needs to be pinned down before an unmanaged function can write to it. But if you declare it on the stack, it's not movable and so it doesn't need to be pinned down.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
Quote:
if I have this right, pd3ddevice is a member of a ref class. That means that the pointer itself is on the managed heap, and needs to be pinned down before an unmanaged function can write to it.


Ah. That makes sense. Thanks.

So you are just suggesting:

// Use local pointer to create.
IDirect3DDevice9* dev;
pd3dObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING, pd3dPP, &dev);

// Save pointer...
pd3dDevice = dev;


That works, but you say I am better off with this route? Is there anything wrong with pin_ptr, or is it just generally best to avoid it if there is an easy alternative?

-----Quat
Pinning isn't free. This way is very nearly free.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.

This topic is closed to new replies.

Advertisement