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

2020-02-01 18:54发布

I know that it's possible to compile my C code into a dll, and then use P/Invoke to call that code.

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...

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. Can anyone confirm or deny this?

Thanks.

4条回答
我欲成王,谁敢阻挡
2楼-- · 2020-02-01 19:25

IMHO, it is not possible, since C is an unsafe and unmanaged language. Besides, C# has all the important features of C except pointers.

查看更多
混吃等死
3楼-- · 2020-02-01 19:27

You can write and compile your C code as a normal (non-.NET) assembly, then P/Invoke it:

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

public int DoSomething(int value)
{
    return do_something_in_c(value);
}
查看更多
Lonely孤独者°
4楼-- · 2020-02-01 19:40

It's not possible. While C# supports unsafe code (pointers), it is not backwards compatible with C or C++

查看更多
smile是对你的礼貌
5楼-- · 2020-02-01 19:42

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. What you're looking to do is not supported by the C# compiler.

查看更多
登录 后发表回答