2

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?

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

This link is unfortunately dead now.
0

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

Comments

0

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;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.