user1814023
user1814023

Reputation:

Migration from C++ to C#, related to pointers

I am C++ programmer, and I am working on a migration project where I need to convert C++ code to C# and I have little knowledge on C#.

The C++ code that I am migrating is having lot of pointer operations such as

Hdr->States = (DspState*)baseAddress; // Converting the buffer to other type.

My question is,

  1. Is there any harm if I do unsafe programming in C# as long as I keep track of memory properly.
  2. Or is there any other way in C# to handle these kind of pointer operations (sometimes double pointers).

Upvotes: 3

Views: 205

Answers (2)

Wolfgang Ziegler
Wolfgang Ziegler

Reputation: 1685

If you are porting a project from C++ to C# your first goal should be to stay completely withing the safe world of managed code. Just because you were using pointers in your C++ code does not mean you have to do the same in C#. Unsafe code in C# should actually be your very last option and only be necessary in very special situations.

The code in your example could like like this in C# and does not need any pointers or unsafe operations whatsoever.

BaseAddress baseAddress = ...
Hdr->States = (DspState)baseAddress;

or as type-checked cast operation

Hdr->States = baseAddress as DspState;

C# / .NET uses references all the time, which are in a way like pointers but without the dangers of pointer arithmetics.

Upvotes: 2

Doctor_Why
Doctor_Why

Reputation: 61

C# authorize the unsafe context in order to allow the use of pointer so if your code was working in c++ it should do fine in c# but depending on whatt you want to do it is not necessary the best solution. For exemple if you use a c++ library which exist in c# you may have to use pointer in c++ but in c# references are used instead. If the kind of operation that you show in post are the only one you use, i think you shouldn't use an unsafe context juste to reference and dereference pointer and you should do a full conversino of your code.

Upvotes: 0

Related Questions