c++ dll导出函数返回false值C#却认为是true的处理方法

转发网址https://stackoverflow.com/questions/1792581/c-from-c-c-function-in-a-dll-returning-false-but-c-sharp-thinks-its-tr

在C++中声明导出函数

bool Foo()
{
  return false;
}

在C#中引用代码

public class FooAPI
{
    [DllImport("Foo.dll")]
    public static extern bool Foo();
}

//......

bool b = FooAPI.Foo(); 
if (!b) 
{ 
    // Throw an exception 
} 

在Foo函数返回值为true时一切正常,当返回值为false时C#获取的值依然为true,其解决方法是在引入函数时增加返回修饰

public class FooAPI
{
    [DllImport("Foo.dll")]
    [return: MarshalAs(UnmanagedType.I1)]
    public static extern bool Foo();
}

注意不能使用[return: MarshalAs(UnmanagedType.Bool)]

猜你喜欢

转载自blog.csdn.net/sdhongjun/article/details/82981656