来自C#的C ++:C ++函数(在DLL中)返回false,但是C#认为这是真的! [英] C++ from C#: C++ function (in a DLL) returning false, but C# thinks it's true!

查看:109
本文介绍了来自C#的C ++:C ++函数(在DLL中)返回false,但是C#认为这是真的!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小的C#应用​​程序,该应用程序调用C ++ API中的一些函数.我将C ++代码构建到DLL中,并且C#代码使用DllImport调用API. (我在C ++ DLL中使用的是.DEF文件,因此不需要外部"C".)

I'm writing a little C# app that calls a few functions in a C++ API. I have the C++ code building into a DLL, and the C# code calls the API using DllImport. (I am using a .DEF file for the C++ DLL so I don't need extern "C".)

到目前为止,API具有一个功能,目前绝对不执行任何操作:

So far the API has one function, which currently does absolutely nothing:

bool Foo()
{
  return false;
}

在C#中,我有以下内容:

In C#, I have the following:

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

...

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

我的问题是,由于某种原因,b总是求值为 TRUE .我在if(!b)上有一个断点,调试器将其报告为"true",与C ++函数返回的内容无关.

My problem is that, for some reason, b is always evaluating to TRUE. I have a breakpoint on if (!b) and the debugger reports it as 'true', irrelevant of whatever the C++ function is returning.

C#bool是否与C ++ bool相同?尽管即使不是这种情况,但我仍然不知道它如何找到返回值为'true'的方法:)

Is the C# bool the same as the C++ bool? Though even if this wasn't the case, I still don't get how it would find the return value to be 'true' :)

有人能帮助我解决这个奇怪的差异吗?

Can anyone help me with this bizarre discrepancy?

提前谢谢!

推荐答案

尝试[return: MarshalAs (UnmanagedType.I1)].默认情况下,C#互操作将C#bool封为Win32 BOOL ,与int相同,而C ++ bool是一个字节的AFAIR.因此,C#的默认封送处理期望返回值是eax寄存器中的BOOL,并拾取一些非零垃圾,因为C ++ bool是在al中返回的.

Try [return: MarshalAs (UnmanagedType.I1)]. By default, C# interop marshals C# bool as the Win32 BOOL, which is the same as int, while C++ bool is one byte AFAIR. Thus, C#'s default marshaling expects the return value to be a BOOL in the eax register, and picks up some non-zero garbage because C++ bool is returned in al.

这篇关于来自C#的C ++:C ++函数(在DLL中)返回false,但是C#认为这是真的!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆