Import a C++ .lib and .h file into a C# project?

前端 未结 3 2215
北海茫月
北海茫月 2020-12-10 10:28

I have just started a C# project and want to import a C++ .lib and it\'s corresponding header (.h) file.

I\'ve read various posts that all mention .dll, rather than

3条回答
  •  臣服心动
    2020-12-10 10:56

    This is, unfortunately, a non-trivial problem.

    The reason is primarily due to the fact that C++ is an unmanaged language. C# is a managed language. Managed and unmanaged refers to how a language manages memory.

    • C++ you must do your own memory management (allocating and freeing),
    • C# .NET Framework does memory management with a garbage collector.

    In your library code

    You must make sure all of the places you call new, must call delete, and the same goes for malloc and free if you are using the C conventions.

    You will have to create a bunch of wrapper classes around your function calls, and make sure you aren't leaking any memory in your C++ code.

    The problem

    Your main problem (to my knowledge) is you won't be able to call those functions straight in C# because you can't statically link unmanaged code into managed code.

    You will have to write a .dll to wrap all your library functions in C++. Once you do, you can use the C# interop functionality to call those functions from the dll.

    [DllImport("your_functions.dll", CharSet = CharSet.Auto)]
    public extern void your_function();
    

提交回复
热议问题