A way How to Compile C library into .Net dll?

前端 未结 4 1209
别那么骄傲
别那么骄傲 2021-01-05 23:22

Can we compile C library as .Net dll (containing and opening access to all C libs functions) by just compiling cpp project containing code like

extern \"C\"         


        
相关标签:
4条回答
  • 2021-01-05 23:38

    It really depends on your C code.

    P/Invoke is often the easiest to start with, and IMO is pretty workable for a handful of functions. Performance isn't necessarily great, and I wouldn't construct an entire program out of it - but to reuse some functions, it's worthwhile.

    Going from C to /clr:pure requires you to:

    1. Convert your C code to C++
    2. Convert your C++ code to Visual C++
    3. Compile with /clr option
    4. Compile with /clr:pure

    The current state of your code (and it's libraries) will dictate how painful that process is.

    0 讨论(0)
  • 2021-01-05 23:47

    This may be of interest to you: Compiling your C code to .NET

    Create a C compiler occil.exe

    To create a .NET dll from a c code e.g stack.c

    Step1: build stack.c to IL code

    occil /ostackdll.il /c /Wd /9 /NStackLib.Stack stack.c
    

    Step2: build to generated IL code to .NET DLL

    ilasm /DLL stackdll.il
    

    Then you can reference the stack.dll in a c# program and call the C function in stack.c

    0 讨论(0)
  • 2021-01-05 23:48

    I found it is the best to use the old style Managed C++ for this.

    CLR:PURE just wont cut it.

    Example:

    extern "C" int _foo(int bar)
    {
      return bar;
    }
    
    namespace Bar
    {
      public __gc class Foo
      {
      public:
        Foo() {}
    
        static int foo(int bar)
        {
          return _foo(bar);
        }
      };
    };
    

    Compile with: /clr:oldSyntax

    Now you can reference the assebmly, and call Bar.Foo.foo() from .NET.

    0 讨论(0)
  • 2021-01-06 00:03

    It's not generally a given that you can even compile C code as C++ without making some changes. If you can get your C code to compile as C++, then you can try getting it to compile as C++/CLI (that's what the clr:pure option does).

    At that point, you can create some kind of class which exposes all your exported functions as static methods of a public (managed) class.

    Some flavours of this sort of stuff can be done with C++ preprocessor tricks (macros, etc), sometimes you end-up writing wrappers manually.

    So the basic information that you can compile C++ into .NET assemblies using /clr:xxx options is true, but that doesn't mean it's the only thing you need to do to get a useful .NET assembly.

    0 讨论(0)
提交回复
热议问题