在C#中调用托管和非托管代码的问题

 

C#中使用非托管指针*
 
值针可以在带有unsafe的函数中正常使用。
必须在函数前,static关键字后加入unsafe关键字。如
static unsafe void Main(string[] args)
{}
在项目属性中,选中Allow unsafe code复选框。
C#中使用托管跟踪句柄^
 
跟踪句柄可以直接赋值到C#对象中。

  在C#中调用托管和非托管代码的问题_第1张图片 

 

 

如果使用 int handle = CalRef.GetHandle();
会出现编译错误:Cannot implicitly convert type 'System.ValueType' to 'int'
这是因为CalRef是使用C++/CLI写的。C++/CLI的int类型是iso-C++的类型,而不是System命名空间下的类。而C#中没有那种ISO-C++类型,所有的整型都是System命名空间下的sealed类,即C#下int就是System::Int32。所以不能进行隐式类型转换。
此时必须进行强制类型转换:
Int32 dsfa = (Int32)(calref.GetHundle());
而在C++/CLI中就可以隐式类型转换。
在C++/CLI中定义:
public    ref   class   CalRef
    
{
        
// TODO: Add your methods for this class here.
    public:
        
~CalRef()
        
{
//            delete[] _value;
        }

        
int* GetValue(){    return _value;}
        
int^ GetHundle(){    return _handle;}
        
static CalRef^ GetInstance()
        
{
            
if(m_Instance==nullptr)
                m_Instance 
= gcnew CalRef();
            
return m_Instance;
        }

    
private:
        
static CalRef^ m_Instance;
        
int* _value;
        
int^ _handle;
        CalRef()
        
{
//            _value = new int[100];
            _value = new int(10);
            _handle 
= gcnew int(100);
        }


    }
;
 
在C#中:
class  Program
    
{
        
static unsafe void Main(string[] args)
        
{
          CalRef calref 
= CalRef.GetInstance();        //OK
       int *res = (calref.GetValue());                //ok
        Int32 dsfa = (Int32)(calref.GetHundle());    //OK
        }

    }

你可能感兴趣的:(在C#中调用托管和非托管代码的问题)