本文介绍了从C#谈话到C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C(不是C ++)中实现的遗留code。我希望能够调用该C code的一些方法从我的C#code(在Windows上)。什么是两种语言之间的接口的最佳方法?请注意,在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. 初始化()=>这将初始化从文件中的数据结构和数据装载到存储器中。这种方法将被调用一次。

  2. ComputeSomething(参数)=>将有来自C#此方法几个电话。

请注意:这两种方法实际上是调用其它几种方法,但这些都只是这两种方法,我们希望暴露给C#(的code是相当复杂的,这就是为什么我们不希望移植到C#)

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#)

我已经能够导入的C code到Visual Studio,并能够成功编译code。我知道,我们或许可以实现C code作为窗口服务,但我要寻找一个解决方案,使我们能够从C#直接调用C的方法。任何指针是高度AP preciated! (是与我所希望做的COM互操作?)

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?)

推荐答案

听起来像是你可以使用的P / Invoke 这一点。看看这个网站的提示:

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

此外,尝试搜索 SO 有关的P / Invoke 谷歌为

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

C#的PInvoke调用C code

我没有手头任何技术的例子,但我已经写了一些.NET code它通过的P / Invoke 所谓的Win32 API的。最棘手的部分越来越传递参数时签名纠正方法。 可能会帮助你在那里。

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.

这篇关于从C#谈话到C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:40