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/archive/2010/12/27/PInvoke.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值