all groups > dotnet interop > november 2007 >
You're in the

dotnet interop

group:

Marshaling a bool from unmanaged to managed code


Marshaling a bool from unmanaged to managed code J.R. Heisey
11/26/2007 2:04:10 PM
dotnet interop: I have a DLL that takes a pointer to a callback function of type:

typedef void ( __stdcall * StdMyCallback_T)(void* context, const char *
sName, bool bState,
EError error, const char * pErrorMsg);

I have defined a delegate as such:

public delegate void MyCallbackDelegate(IntPtr iPtr, IntPtr sName,
[In,MarshalAs( UnmanagedType.I1 )] bool bState, Error error,
IntPtr sErrorMsg);

The callback function in managed code is defined as:

private void CDCI_My_Callback_Handler(IntPtr iPtr, IntPtr sName, bool
bState,Error error,
IntPtr
sErrorMsg)
{
MyEventArgs evt = new MyEventArgs(sName, bState,error,
sErrorMsg);
... // other stuff
}

However the bState parameter is not properly marshaled. In the MarshalAs
directive I've also tried UnmanagedType.Bool. When I look at the assembly
code in the C++ based unmanaged DLL for the parameter bState, I see the al
register getting set then eax register is pushed onto the stack. Three extra
bytes with undefined values are pushed. I expect for memory alignment
reasons. Now how do I get the Managed code to marshal the bool parameter
properly?

Microsoft you listening?

Thanks,
J.R. Heisey

Re: Marshaling a bool from unmanaged to managed code J.R. Heisey
11/26/2007 7:03:29 PM
According to the on line help it said I1. However your assertion is
validated in

http://msdn2.microsoft.com/en-us/library/ms182206(VS.80).aspx.

However I was able to get it working after I found other instances of
bool parameters in functions defined in the same unmanaged DLL. When I
explicitly specified the marshaling of these bools my callback started
working. Perhaps there was some stack corruption due to the unmarshaled
parameter.

Hmm ... looking over my code I use U1 in most cases and in the callback
I'm using I1. Seems to work but I will revert the I1 to U1 for consistancy.

Thanks,

[quoted text, click to view]
Re: Marshaling a bool from unmanaged to managed code Michael Phillips, Jr.
11/26/2007 7:44:07 PM
Did you try using UnmanagedType.U1 to represent bool?

See:
http://msdn2.microsoft.com/en-us/library/t2t3725f.aspx

[quoted text, click to view]

Re: Marshaling a bool from unmanaged to managed code William DePalo [MVP VC++]
11/27/2007 9:16:52 PM
[quoted text, click to view]

I hope there's a way.

FWIW: I can tell you that returning C++ bools ( as a return value not as an
writable argument ) from native to managed code was not possible for me with
the 1.1 version of framework (
http://www.codeproject.com/buglist/virtualboolbug.asp ) and managed
extensions for C++. My code is liberally sprinkled with lines like

_asm xor eax, eax ; clear all thirty two bits

to get things to work. It was either that or change the type from bool to
BOOL.

Regards,
Will

AddThis Social Bookmark Button