如何从 C 程序中使用现有的 C# 代码
有没有办法可以开发一个示例 C# 程序,并将其制作为 DLL,然后在我的 C 程序中使用它?
比如说,C# DLL 有一个函数 add(int a, int b)
,它返回或打印结果。我想在我的 C 程序中使用它。任何示例链接都应该有很好的帮助。
Is there a way I can develop a sample C# program, and make it a DLL, and use it in my C program?
Say, C# DLL has a function add(int a, int b)
which returns or prints the result. I want to use this in my C program. Any example link should be a good help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个解决方案。该解决方案提供了 [DllExport] 属性,允许从 C 调用 C# 函数。
https:// /sites.google.com/site/robertgiesecke/Home/uploads/unmanagementexports
C# 代码
C 代码
Here is a solution. The solution provides [DllExport] attribute that aallows to call C# function from C.
https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports
C# code
C code
最简单的方法是将 C# DLL 公开为 COM 对象,然后从 C/C++ 应用程序创建它的实例。请参阅MSDN 获取分步指南。
或者,如果您希望能够从中调用 C# DLL 实际上是一个 C++ 应用程序,则可以创建一个混合模式 C++/CLI 应用程序,其中包含托管代码和非托管代码。然后,C++ 应用程序可以直接从托管 C# DLL 调用函数。
另请参阅 MSDN 上的“托管/非托管代码互操作性概述”。
编辑:除了“它在 C 中不起作用”之外没有更多信息,我什至不知道您尝试了上述哪些建议。正如我所建议的,我不确定第二个是否可以直接使用 C(从未尝试过),但我看不出为什么第一个不能。
无论如何,快速但肮脏的修复可能是将 C# 函数包装在 C++ DLL 中,然后从 C 应用程序中调用它。确保将要从 C++ DLL 导出的任何函数声明为
extern
,否则它们的名称将被损坏的 C++ 名称,这在 C 中无法使用。请参阅此处了解更多信息信息: http://www.parashift.com/c++ -faq-lite/mixing-c-and-cpp.htmlThe easiest way to do this is to expose the C# DLL as a COM object, and then create an instance of it from your C/C++ application. See MSDN for a step-by-step guide.
Alternatively, if it's actually a C++ application that you want to be able to call the C# DLL from, you could create a mixed-mode C++/CLI application, which contains both managed and unmanaged code. The C++ application can then call functions directly from the managed C# DLL.
Also see "An Overview of Managed/Unmanaged Code Interoperability" on MSDN.
EDIT: Without any more information than "it doesn't work in C," I don't even know which of the above suggestions that you tried. As I suggested, I'm not certain if the second will work with straight C (never tried it), but I see no reason why the first wouldn't.
Regardless, the quick and dirty fix might be to wrap the C# functions in a C++ DLL, which you then call from your C application. Make sure that you declare any of the functions that you want to export from the C++ DLL as
extern
, otherwise their names will be mangled C++ names, which are impossible to work with in C. See here for more information: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html