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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.