Sign in to follow this  
Quat

c++/CLR Direct3D

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this