I have several C functions that I would like to use in my C# application without having to change them as they already are. Is there a SIMPLE way to use them without having to chop them up into a DLL or is that the only path forward? Can I just link the direct path to where these files live and use them in my C# application?
CodePudding user response:
So you have a bunch of C files lying around your project. They contain functions you want to call from C# code. Fair enough, sure, so let's count the possible ways you can achieve that.
- Rewrite those functions into C#. This might actually be the most sensible option if those functions aren't being used elsewhere (like in a separate C project, for example), because then you don't have to maintain code in two separate languages for the same project. C# also has many advantages over C, like safety and expressiveness, and depending on what those functions are doing, you might not even see a significant performance difference.
- Put that code in a native DLL, export those functions, and use P/Invoke from C# to call them. This is what involves the least modification to the original code.
- Write a C /CLI wrapper that calls those functions, and call the C /CLI code from C#. This is especially useful if you want to present an OOP-style interface to the C# code.
- Use a C interpreter to execute those C files like they were scripts. This will probably be slower, more brittle, harder to maintain, and there might be other restrictions depending on which interpreter you use and what your C code looks like.