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?
Asked
Active
Viewed 75 times
-1
-
Does this answer your question? [Is it possible to embed C code in a C# project?](https://stackoverflow.com/questions/2874603/is-it-possible-to-embed-c-code-in-a-c-sharp-project) – 41686d6564 stands w. Palestine May 05 '22 at 19:22
-
2C is a compiled language. You need to compile that code before you can execute it. Ideally, to a DLL, so that you can then call them through P/Invoke. But otherwise, no, a C# compiler cannot compile C code. The only other approach I can think of is to rewrite the C code into C#, or wrap it in a C++/CLI project. – Etienne de Martel May 05 '22 at 19:22
-
If they're not in a .dll/.so, where are they? – ikegami May 05 '22 at 19:22
-
@ikegami they are in their respective .c files located in a separate directory from the C# application – Justin May 05 '22 at 19:25
-
C is not a language that is interpreted at runtime. How do you expect this to work? Have the C files processed by a preprocessor with what flags? – Cheatah May 05 '22 at 19:30
-
Re "*they are in their respective .c files*", `.c` files contain source code, not executable code. You're asking how to execute functions, so you need them in their executable form. You will need to compile them. – ikegami May 05 '22 at 19:33
1 Answers
1
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.

41686d6564 stands w. Palestine
- 19,168
- 12
- 41
- 79

Etienne de Martel
- 34,692
- 8
- 91
- 111