简体   繁体   English

是否可以在C#项目中嵌入C代码?

[英]Is it possible to embed C code in a C# project?

I know that it's possible to compile my C code into a dll, and then use P/Invoke to call that code. 我知道可以将我的C代码编译成dll,然后使用P / Invoke来调用该代码。

What I wondered if it was possible to have a chunk of C code embedded directly in my code, perhaps only available to one class... 我想知道是否有可能在我的代码中直接嵌入一大块C代码,也许只有一个类可用...

Something like this (non-working) example: 像这样(非工作)的例子:

public class MyClass {
    extern "C" {
        int do_something_in_c(int i) {
            return i*2;
        }
    }

    public int DoSomething(int value) {
        return do_something_in_c(value);
    }
}

I've been trying for a few hours using Visual Studio 2008, but I'm not getting anywhere, and I suspect that it isn't actually possible. 我一直在尝试使用Visual Studio 2008几个小时,但我没有到达任何地方,我怀疑它实际上是不可能的。 Can anyone confirm or deny this? 任何人都可以确认或否认这个吗?

Thanks. 谢谢。

It is possible to create a mixed-mode assembly (that is, one that has both managed and native code), but only the C++/CLI compiler can produce one of these. 可以创建混合模式程序集(即具有托管代码和本机代码的程序集),但只有C ++ / CLI编译器才能生成其中一个。 What you're looking to do is not supported by the C# compiler. C#编译器不支持您要做的事情。

It's not possible. 这是不可能的。 While C# supports unsafe code (pointers), it is not backwards compatible with C or C++ 虽然C#支持不安全的代码 (指针),但它不向后兼容C或C ++

You can write and compile your C code as a normal (non-.NET) assembly, then P/Invoke it: 您可以编写和编译C代码作为普通(非.NET)程序集,然后P / Invoke它:

[DllImport ("mylib.dll")]
private static extern int do_something_in_c(int i);

public int DoSomething(int value)
{
    return do_something_in_c(value);
}

IMHO, it is not possible, since C is an unsafe and unmanaged language. 恕我直言,这是不可能的,因为C是一种不安全和非托管的语言。 Besides, C# has all the important features of C except pointers. 此外,除了指针外,C#还具有C的所有重要功能。

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

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