【问题标题】:Why does my dllimport function always return true? [duplicate]为什么我的 dllimport 函数总是返回 true? [复制]
【发布时间】:2016-06-14 10:48:23
【问题描述】:

我遇到了一个关于从管理不善的 C++ dll 导出的函数的奇怪问题,我在 C# 代码中使用该函数:无论我在 C++ 中返回什么,在 C# 中接收到的返回布尔值始终为真。我缩小了范围,得到了一个包含以下代码的 C++ 文件:

#ifdef __cplusplus
extern "C" {
#endif

    __declspec(dllexport) bool init()
    {
        return false;
    }

#ifdef __cplusplus
}
#endif

我将它构建成一个 dll 并在 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" );
        }
    }
}

当我运行它时,我得到以下输出:

初始化成功

我很困惑。有什么想法吗?

【问题讨论】:

    标签: c# c++ dllimport dllexport


    【解决方案1】:

    bool 是一个可怕的原生类型。每个人都按照自己的方式去做。在 C# 中,bool 上的默认互操作映射到 BOOL C++ 类型,它处理的值与您的 bool 不同。

    您需要使用[return:MarshalAs(UnmanagedType.I1)] 来指定正确的编组,并且不要忘记使用C 调用约定。

    【讨论】:

    • 天哪。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多