[英]How to use existing C# code from C program
Is there a way I can develop a sample C# program, and make it a DLL, and use it in my C program? 有没有办法可以开发一个示例C#程序,并使其成为DLL,并在我的C程序中使用它?
Say, C# DLL has a function add(int a, int b)
which returns or prints the result. 比方说,C#DLL有一个函数
add(int a, int b)
,它返回或打印结果。 I want to use this in my C program. 我想在我的C程序中使用它。 Any example link should be a good help.
任何示例链接都应该是一个很好的帮助。
The 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. 最简单的方法是将C#DLL公开为COM对象,然后从C / C ++应用程序创建它的实例。 See MSDN for a step-by-step guide.
有关分步指南,请参阅MSDN 。
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. 或者,如果它实际上是您希望能够从中调用C#DLL的C ++应用程序,则可以创建混合模式 C ++ / CLI应用程序,该应用程序包含托管代码和非托管代码。 The C++ application can then call functions directly from the managed C# DLL.
然后,C ++应用程序可以直接从托管C#DLL调用函数。
Also see "An Overview of Managed/Unmanaged Code Interoperability" on MSDN. 另请参阅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. 编辑:没有任何更多的信息,而不是“它在C中不起作用”,我甚至不知道你尝试过哪些上述建议。 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.
正如我所说的那样,我不确定第二种是否能用直C(从未尝试过),但我认为没有理由为什么第一种不会。
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. 无论如何,快速而肮脏的修复可能是将C#函数包装在C ++ DLL中,然后从C应用程序调用它。 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 确保您将要从C ++ DLL导出的任何函数声明为
extern
,否则它们的名称将被修改为C ++名称,这在C中是不可能的。请参阅此处以获取更多信息: http:// www .parashift.com / C ++ - FAQ-精简版/混合-C-和-cpp.html
Here is a solution. 这是一个解决方案。 The solution provides [DllExport] attribute that aallows to call C# function from C.
该解决方案提供了[DllExport]属性,允许从C调用C#函数。
https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports
C# code C#代码
class Test
{
[DllExport("add", CallingConvention = CallingConvention.StdCall)]
public static int Add(int left, int right)
{
return left + right;
}
}
C code C代码
int main()
{
int z = add(5,10);
printf("The solution is found!!! Z is %i",z);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.