4

Assume that I have some C code for a portable, non-visual library. The code relies mostly on CRT (there is no QT/DirectX/WinAPI etc. dependencies).

Is there a way I could use this code in a C# application? I know about Managed C++ and that's not an acceptable way for me.

I thought of a C/C++ to C# converter that I could use for automatic translation (I don't need a readable output, a working one is enough) or an emulator that I could use to execute compiled C/C++ code.

Do you know of anything that might help me to use existing C/C++ code from C# code?

EDIT:

P/Invoke is not an acceptable way too. As well as calling external EXE or using COM/ActiveX. I need something that will allow me to incorporate C and C# code into one managed DLL or EXE.

Existing C code is a library (.lib), not an EXE.

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
  • Is this C code a proper executable or just a library? Anyway you could use P/Invoke for C library or execute in case of an exe and catch the output – RedX Jul 02 '12 at 12:45
  • http://stackoverflow.com/questions/935664/possible-to-call-c-code-from-c – Govind Malviya Jul 02 '12 at 12:45
  • Translation is unlikely to be practical, as C# code does not have pointers and translating pointer-based code to non-pointer-based code is virtually impossible to automate. – Thom Smith Jul 02 '12 at 12:50
  • Why is it so critical to have one single file as the output? It's not very usual for windows apps to have a single executable and no accompanying files. – Qnan Jul 02 '12 at 12:57
  • @MikhailKozhevnikov because I know plenty of methods to do this without this restriction ;-) – Bobrovsky Jul 02 '12 at 12:58
  • Based on "Existing code is a `.lib`", do you have source code or not? – Ben Voigt Jul 02 '12 at 13:14
  • @BenVoigt I do have all code required to build a .lib – Bobrovsky Jul 02 '12 at 14:10
  • @Thom: Pointers may not be recommended style in C#, but they certainly do exist. – Ben Voigt Jul 02 '12 at 14:34
  • If you don't need to maintain the code, why won't you create a DLL and reference it... such as COM+ object – Tomer W Jul 02 '12 at 12:47

2 Answers2

7

Why not temporarily compile the C++ as managed C++, to get a .net assembly, then use Reflector to decompile it into pure C#?

Neil
  • 11,059
  • 3
  • 31
  • 56
0

I think it's easiest to use the methods directly from the DLL without converting the code to C#. That works pretty well, one disadvantage being that you have to ship multiple binaries for different platforms. Importing functions from Dll is as easy as

[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress (IntPtr hModule, string procedureName);

I don't think incorporating both C and C# code in one DLL is feasible without converting the former.

Qnan
  • 3,714
  • 18
  • 15