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

本文探讨了在C#编程环境中如何有效地调用托管代码和非托管代码,包括C++库的使用,字符串处理以及内存管理。通过实例解析了System类库的应用,强调了在混合编程中需要注意的类型转换和资源释放问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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

   

 

 

如果使用 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
        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值