简体   繁体   English

C# 中的内联 C 和编译?

[英]inline C in C# and compilation?

Is it possible to write majority of your program in say C# and then drop down and do certain functions/objects in C or C++?是否可以在 C# 中编写大部分程序,然后在 C 或 C++ 中执行某些功能/对象?

I know you can call pre-compiled.dlls from C#;我知道你可以从 C# 调用 pre-compiled.dlls; but can you do 'inline' native C directly from C#?但是你能直接从 C# 做“内联”原生 C 吗? Do they have to be "managed".dlls?他们必须是“托管”.dll吗?

If not, I'm assuming there is a JNI like interface?如果没有,我假设有一个类似 JNI 的接口?

Also, another question;另外,另一个问题; can you compile C# down into "native" machine code?你能把 C# 编译成“本机”机器码吗?

MSVS2010/Win7 if it matters. MSVS2010/Win7 如果重要的话。

You can't inline C code in C# - if you want to write part of your code in C then you will need to cross some sort of interop layer in order to call that C code, for example P/Invoke or Managed C++. You can't inline C code in C# - if you want to write part of your code in C then you will need to cross some sort of interop layer in order to call that C code, for example P/Invoke or Managed C++.

You can however inline C (or even assembly) in Managed C++, allowing you to combine native code and managed code in a single assembly / dll.但是,您可以在托管 C++ 中内联 C(甚至程序集),从而允许您将本机代码和托管代码组合在一个程序集中 / dll。

For the.Net equivalent of JNI, (native code calling managed code) the normal method is to either use COM interop or Managed C++ - you can also host the CLR, but this is less common.对于 JNI 的 .Net 等效项(本机代码调用托管代码),通常的方法是使用 COM 互操作或托管 C++ - 您也可以托管 CLR,但这不太常见。

As for compiling C# down into "native" machine code, read up on NGen .至于将 C# 编译为“本机”机器代码,请阅读NGen

Native C/C++ can be called using PInvoke (DllImport) from C#, or by C++/CLI code (.NET C++) or via COM.可以使用 C# 中的 PInvoke (DllImport) 或通过 C++/CLI 代码 (.NET C++) 或通过 COM 调用本机 C/C++。 This is referred to as interop.这称为互操作。

PInvoke requires native code to be exposed via DllExport. PInvoke 需要通过 DllExport 公开本机代码。

C++/CLI and native code can be placed in same DLL or even cpp file. C++/CLI 和本机代码可以放在同一个 DLL 甚至 cpp 文件中。

C# (.NET) code is compiled to MSIL, which is translated on first access to machine code (JIT). C# (.NET) 代码编译为 MSIL,在首次访问机器代码 (JIT) 时进行翻译。 It can be stored in advanced in GAC already translated to machine code, however, that only improves first access.它可以存储在已经翻译成机器代码的 GAC 中,但是,这只会改善首次访问。

The equivalent C# code to C code should perform the same.与 C 代码等效的 C# 代码应该执行相同的操作。 C# even allows pointers in unsafe code, however not with templates as C++ does. C# 甚至允许在不安全代码中使用指针,但不能像 C++ 那样使用模板。

MSIL even has optimization that enable improving performance on dome cases. MSIL 甚至进行了优化,可以提高圆顶外壳的性能。

I have seen demos of parallel calculations run faster in C# than equivalent C++.我已经看到在 C# 中并行计算的演示比等效的 C++ 运行得更快。

If you design your C# wisely, performance will be good.如果您明智地设计 C#,性能会很好。 Same goes to native C/C++.本机 C/C++ 也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM