P/Invoke 返回bool 值

在平台调用时,会遇到被调用的函数返回的是bool值,这时使用C#调用时便会得到错误的bool值,在网上查了一下,有2种解决方法

1.定义被调用函数时不返回bool,直接回返回int.

2.在声明方法时加一个 [return: MarshalAs(UnmanagedType.I1)]

我的示例代码:

C++ 编写的示例程序代码(Win32 DLL):

编译完成后,生成一个名为 DllTest.dll 的 DLL

_declspec(dllexport) int Test (int i)
{
    
return i;
}

_declspec (dllexport) 
bool TestBool(int i )
{
    
if(i==0)
    {
        
return false;
    }
    
else
    {
        
return true;
    }
}

C#调用端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
    
class Program
    {
        [DllImport(
"DllTest.dll", EntryPoint = "?Test@@YAHH@Z")]
        
static extern int Test(int i);

        [DllImport(
"DllTest.dll", EntryPoint = "?TestBool@@YA_NH@Z")]
        [
return: MarshalAs(UnmanagedType.I1)]
        
static extern bool TestBool(int i);

        
static void Main(string[] args)
        {
            
int test1 = Test(50);
            
int test2 = Test(-10);
            
int test4 = Test(0);
            
int test3 = Test(30);
            
int test5 = Test(-60);
            
int test6 = Test(30);

            
//int test11 = TestBool(50);
            
//int test21 = TestBool(-10);
            
//int test41 = TestBool(0);
            
//int test31 = TestBool(30);
            
//int test51 = TestBool(-60);
            
//int test61 = TestBool(30);

            
bool test11 = TestBool(50);
            
bool test21 = TestBool(-10);
            
bool test41 = TestBool(0);
            
bool test31 = TestBool(30);
            
bool test51 = TestBool(-60);
            
bool test61 = TestBool(30);
        }
    }
}

有些朋友可能不知道我的入口点是怎么来的,为什么是一串奇怪的字符串,

我是通过 Depends 工具找到的,呵呵

如下图

如果不加

 [return: MarshalAs(UnmanagedType.I1)]

那么返回的bool值就会是错的,而int就不会有这种现象,它是与各语言表示bool 的位长相关的。

了解更多可查看

http://bytes.com/topic/c-sharp/answers/267443-unmanaged-c-dll-c-bool-return-problem

http://connect.microsoft.com/VisualStudio/feedback/details/355665/native-c-function-returning-bool-always-return-true-in-net-interop

http://msdn.microsoft.com/en-us/library/t2t3725f.aspx

原文地址:https://www.cnblogs.com/hbhbice/p/PInvoke.html