Is there a C#'s unsafe equivalent in C++/CLI?

痞子三分冷 提交于 2019-12-22 08:23:37

问题


I am trying to port C++/CLI code into Verifiable Type-Safe C++/CLI code (Use clr:safe flag) so I can get a AnyCPU assembly. The main compilation problem I find is that, I get a lot of C4956 errors and I think, that might be solved by explicitly tell the compiler I expect this to be unsafe. Suggestions?


回答1:


This has been covered here

Basically, this is what /clr:pure was supposed to provide, because it also generates a pure MSIL assembly. Unfortunately it still causes a dependency on a particular bitness, so isn't compatible with AnyCPU.




回答2:


You shouldn't have many problems porting unsafe code from C# to CLI, just be sure to use IntPtr which is a CLS-compliant architecture agnostic pointer.

If you run into specific problems or if you're unsure about something, update the question with more details.




回答3:


C++/CLI can be freely mixed with C++ code and is inherently unsafe, so there's no equivalent needed except the language itself. Use pin_ptr to pin down garbage collected objects and buffers and you now have a C++ style pointer to use. You can also use C++ STL, unsafe casts, etc. on such pointers.




回答4:


For your reference on answering this question we have:

/clr:safe Creates an MSIL-only verifiable assembly. You can’t have native types in your code, and if you try to use them, the compiler will throw an error. This compilation mode produces assemblies that are equivalent to what C# (regular mode) and VB.NET would produce.

In order to work with type-safe code you need to use handles (using gcnew) instead of pointers (using new)

Also, safe_cast operator is new to C++/CLI and replaces __try_cast in the old syntax. safe_cast is guaranteed to produce verifiable MSIL. You can use safe_cast wherever you would typically use dynamic_cast, reinterpret_cast, or static_cast. At runtime, safe_cast checks to see if the cast is valid

You should grab a copy of: C++/CLI in Action by Nishant Sivakumar Very nice reference of C++/CLI



来源:https://stackoverflow.com/questions/6792315/is-there-a-cs-unsafe-equivalent-in-c-cli

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