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

I know that you can compile my C code in a dll and then use P / Invoke to call that code.

What I was wondering is is it possible to have a piece of C code embedded directly in my code, possibly only available for 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 have been trying for several hours to use Visual Studio 2008, but I will not go anywhere, and I suspect that this is actually not possible. Can anyone confirm or deny this?

Thanks.

+7
c c # visual-studio-2008 embed
source share
4 answers

You can create a mixed-mode assembly (that is, one that has both managed and native code), but only the C ++ / CLI compiler can create one of them. What you want to do is not supported by the C # compiler.

+9
source share

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

+3
source share

You can write and compile your C code as a regular (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); } 
+2
source share

IMHO, this is not possible, since C is an unsafe and unmanageable language. In addition, C # has all the important C functions except pointers.

0
source share

All Articles