Calling C# (.NET) APIs from C
开发者_StackOverflow中文版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?
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.
There is solution that can avoid using COM or C++\CLI. See here: Calling A .NET Managed Method from Native Code
you can turn c# code into COM, or use C++\CLI.
Here is a solution. It implements [DllExport] attribute https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports
So one can do something like this to call managed code from unmanaged code:
C# code
class Test
{
[DllExport("add", CallingConvention = CallingConvention.StdCall)]
public static int Add(int left, int right)
{
return left + right;
}
}
C code
int main()
{
int z = add(5,10);
printf("The solution is found!!! Z is %i",z);
return 0;
}
精彩评论