Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Unmanaged to managed: bool gives error

Problem concerns the marshalling of datatype 'bool' from unmanaged C++ to managed C++.

This is a native C++ class, compiled without /clr:

class CmClip
{
  public:
    virtual bool runtest()
    {
      return false;
    }
};

Then I try to access it from a managed __gc class (in another assembly) like this:

CmClip * pClip = new CmClip();
bool b = false;
b = pClip->runtest();

The expected value of b is 'false'. However, it is 'true'.

How to solve this? This is not the result that is expected. (I would very much like to keep the unmanaged code untouched.)

I have tried:
remove the 'virtual' keyword from the function runtest(). Result: all works correctly, b = false. But I touched the original code.

I have tried:
change the return type from bool to BOOL. Result: again all works correctly. But I touched the original code.

I have tried:
storing the return value from runtest() in an integer. Result: does not work, integer is set to value 0x1.

I am aware that a native bool has size 1 byte, whereas a managed bool always has size 4 bytes. This could partly explain, but not excuse, why I get a wrong return value.

Does anyone have a deeper explanation for this? Or maybe even a solution? I would like to 'solve' this purely from the managed side, and prefer to not make changes in the original code.

Best regards,

Stephen Muires

Stephen Muires
Wednesday, April 16, 2003

If anyone has trouble reproducing the error here is a demo cpp file that can compile on its own and demonstrates the error:

//compile with cl.exe version 13.00.9466:
//  cl /clr managedbool.cpp
//expected output: 'False'
//actual output: 'True'
#using <mscorlib.dll>
#include <tchar.h>

using namespace System;

#pragma unmanaged

class UnmanagedClass
{
  public:
    virtual bool runtest()
    {
      return false;
    }
};

#pragma managed

int _tmain(void)
{
  UnmanagedClass * tester = new UnmanagedClass();
  Boolean result = tester->runtest();
  Console::WriteLine( result.ToString() );
  return 0;
}

Stephen Muires
Wednesday, April 16, 2003

No solution to the bug, just confirming it's still a bug with .NET v1.1 and VS.NET 2003.

Brad Wilson (dotnetguy.techieswithcats.com)
Wednesday, April 16, 2003

This is a known bug... someone reported it quite a while ago in the microsoft.public.dotnet.languages.vc newsgroup, and the VC++ team is aware of it.

No idea exactly why it didn't make it for Everett, though...

Tomas Restrepo
Wednesday, April 16, 2003

*  Recent Topics

*  Fog Creek Home