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

被折叠的 条评论
为什么被折叠?



