• Create Account

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

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

2 replies to this topic

### #1CAPE  Members

150
Like
0Likes
Like

Posted 13 January 2013 - 07:45 AM

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

### #2web383  Members

804
Like
0Likes
Like

Posted 13 January 2013 - 07:19 PM

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?

### #3Washu  Senior Moderators

7714
Like
1Likes
Like

Posted 13 January 2013 - 08:06 PM

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.
ScapeCode - Blog | SlimDX

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.