I got a weird issue regarding a function exported from a mismanaged C++ dll, which I use from C# code: the returned bool received in C# is always true, no matter what I return in C++. I narrowed it down and got a C++ file containing the following code:
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) bool init()
{
return false;
}
#ifdef __cplusplus
}
#endif
I build it into a dll and import the functions in C#:
using System;
using System.Runtime.InteropServices;
namespace Test
{
class TestDll
{
[DllImport( "dlltest_d" )]
public static extern bool init();
}
class Program
{
static void Main( string[] args )
{
if( !TestDll.init() )
{
Console.WriteLine( "init failed" );
return;
}
Console.WriteLine( "init succeeded" );
}
}
}
When I run this, I get the following output:
init succeeded
I'm quite puzzled. Any ideas?
bool
is a horrible native type. Everyone does it their own way. In C#, the default interop on bool
maps to the BOOL
C++ type, which deals with different values than your bool
.
You need to use [return:MarshalAs(UnmanagedType.I1)]
to specify the correct marshalling, and don't forget to use the C calling convention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With