C# and void pointers

你说的曾经没有我的故事 提交于 2019-12-01 16:39:41

Typically, for marshaling situations, using IntPtr would be the preferred approach here. It is allowed in safe code, and makes it very clear that your intention is marshaling a pointer back and forth.

This is how much of the BCL represents handles. For example, you can construct a Cursor from an IntPtr representing the native handle.

The basic rule is if you need to interact with it as a pointer in c# use unsafe code/pointers. If you can treat it as an opaque handle use an IntPtr. You would use ref if you need to pass a pointer to a structure to unmanaged code.

Unsafe is an instruction to compiler that there will be pointers in this context. From MSDN

In the common language runtime (CLR), unsafe code is referred to as unverifiable code. Unsafe code in C# is not necessarily dangerous; it is just code whose safety cannot be verified by the CLR. The CLR will therefore only execute unsafe code if it is in a fully trusted assembly. If you use unsafe code, it is your responsibility to ensure that your code does not introduce security risks or pointer errors.

I have used it since .net 1.1 while using an C++ API in C# which used to talk to mainframes through COM Port of PC :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!