In addition to all answer above that are really good, I would add some tricks that might help you.
How well it work would depends a lot on the original code. Would it be a good idea to convert it? This also depends. That kind of conversion might works relatively well for mathematical stuff or maybe encryption. On the contrary, it would not works well if your code depends on many C libraries, complex macros...
It would be up to you to evaluate which option is best:
- Try to convert the code manually.
- Rewrote the whole code in C# (and only use the old code as a reference).
- Put your C code in a DLL and use it either with P/Invoke or mixed-mode assembly.
You could start by copying the existing C code in a C# file and put all function in a class. Make that class
static
and all functions
public static
.
Remove includes and other specific C stuff.
For each function in C code, make a
private static
function with the exact same name as the original one. For example:
public static class ConvertCodeInC {
private static double fabs(double x) => Math.Abs(x);
private static void more_complete_function_here(int value)
{
}
}
The you can also convert macros to constants or functions as appropriate. Update types.
Many of that can be done with find and replace. For example, replace
unsigned int
with
uint
. Also replace
->
with
.
.
Once the program is converted, you can do Rename method to remove useless temporary functions like
fabs
in my example. If the function is used only a few times and is trivial, it would be simpler to immediatly update it to call the .NET equivalent function.
Be aware that things like find and replace might be somewhat dangerous in a case like that so save often and confirm each change if necessary.
Once the code is compiling, you can then make it more .NET by refactoring it to use .NET naming convention for example.