HowTo: Send HWND from managed C# to unmanaged C++

Started by
1 comment, last by Washu 11 years, 3 months ago

I'm currently implementing a render system that are scriptable by XML. While the system is kinda awesome, so far, there is a bit of a steep learning curve for others to use the scripts. So I'm in the process to also implement a editor to the render system. The render system is implemented in C++, the editor will be implemented in Windows Forms (C#).

But im already stumped. I try to call the functions from the dll, but i get a


PInvokeStackImbalance was detected.

error. While reading on about the error, I realize that there is a problem with calling conventions and parameters, or, like the error tells me:


This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

But, there should match, or am I at fault here?

The call is the following:


        [DllImport(DllName, SetLastError = true)]
        static unsafe extern void Initalize(IntPtr hWnd);
        public unsafe void Start(IntPtr hWnd)
        {
            Initalize(hWnd);
        }

The dll entry is as follow:


	namespace hs
	{
		namespace renderer
		{
			[...]

			__declspec(dllexport) void Initalize(HWND hWnd);

			[...]
		}
	}

I'm, as I said, stumped. First i thought it was the namespaces, but as it finds the entry point, i don't think thats the problem.

Anyone out there who knows the correct way to do this?

Much appreciated.

David Gustavsson
Developer on "Hello space"
IndieDB
Advertisement

Try passing the HWND as an Int32 and cast it back to HWND on the unmanaged side.

Unmanaged code:


public unsafe void Start(IntPtr hWnd)
{
     Initalize(hWnd.ToInt32());
}

On the unmanaged side:


void Initalize(int handle)
{
     hwnd = (HWND)handle;    
}

Does that work?

The error you're getting is because you have not bothered to indicate to the runtime the appropriate CALLING CONVENTION it should use.

Furthermore, from the export, I cannot tell if you're exporting as cdecl or other.

As a note to the previous poster, the HWND should be passed as an IntPtr.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

This topic is closed to new replies.

Advertisement