tags:

views:

94

answers:

3

To invoke a C API from C# I would use P/Invoke. But if I were to do the reverse, call .NET APIs from C, how would I go about it?

A: 

you can turn c# code into COM, or use C++\CLI.

Benny
+2  A: 

If you really want to do it all through C APIs and do an end run around COM and C++ you could do the following. But first figure out if it's truly necessary! I suspect in most cases it won't be.

Step 1. Create the C# .Net assembly you wish to call.

Step 2. Create a mixed mode CLI/C++ assembly with extern "C" functions exported. Have this assembly call the C$ assembly.

Step 3. Create your C application that calls the exported C style functions from the DLL made in step 2.

Things to consider. A. Is there an actual NEED to have a C (versus C++/COM) app directly call a .Net assembly?
In other words, why not use C++ and COM to COM exported .Net methods if you really must have a mixed (.Net and non-.Net) application/system?

B. Will the APIs you write be wrappers on classes? If so, how will you manage their life times? (e.g. Will you create/use handles? How will you manage their relationships to the actual gc objects...etc)

C. Strings. These are handled very different between C and .Net. Make sure you're familiar with their differences and how to properly send strings across these boundaries...Hint: CString is your friend.

Jason D
+1  A: 

There is solution that can avoid using COM or C++\CLI. See here: Calling A .NET Managed Method from Native Code

stasetz