Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my dllimport function always return true? [duplicate]

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?

like image 654
iko79 Avatar asked Sep 06 '25 19:09

iko79


1 Answers

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.

like image 157
Luaan Avatar answered Sep 08 '25 09:09

Luaan