Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

talking to C from C#

Tags:

c

c#

I have a legacy code implemented in C (not C++). I would like to be able to call a few methods in this C code from my C# code (on Windows). What would be the best approach to interface between the two language? Please note that the method in C is not stateless. We need to call two methods:

  1. initialization() => this will initialize the data structure and load data from files into memory. This method will be called once.
  2. ComputeSomething(parameters) => there will be several calls from C# to this method.

Note: These two methods actually call several other methods but these are only the two methods that we would like to expose to C# (the code is quite complicated, that's why we do not want to port to C#)

I have been able to import the c code into visual studio and able to compile the code successfully. I know that we can probably implement the C code as windows service but I am looking for a solution that allow us to call C method from C# directly. Any pointers is highly appreciated! (is COM interop related to what I am looking to do?)

like image 953
mwong Avatar asked Jul 14 '10 22:07

mwong


People also ask

What is C-level conversation?

The conversation is a dialogue — not a monologue. Listen, show respect, come prepared, and get to the heart of the matter, and you'll master connecting with the C-suite in no time at all.


1 Answers

Sounds like you can use P/Invoke for this. Check out this site for tips:

http://www.pinvoke.net/

Also, try searching SO for advice on P/Invoke and Google for

c# pinvoke calling c code

I don't have any technical examples at hand, but I have written some .NET code which called Win32 API's via P/Invoke. The tricky part is getting the method signatures correct when passing parameters. This might help you out there.

like image 169
Jason Evans Avatar answered Nov 15 '22 02:11

Jason Evans