Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call c++ library from c#

Tags:

c++

c#

unmanaged

This question might seem a repeat of previous ones. I have read through a series of posts, but not completely clear for my situation.

I have a c++ library which is created using momentics IDE. I have to be able to use this library into a c# project.

Someone had been working on this project before being handed over to me. Currently, there are 2 layers for making this possible. First, a c++ project includes the complete library with a c++ wrapper. This project creates a dll as the output. This c++ dll is then fed to a c# project, which has dllimport calls to the c++ dll. This c# project again creates a dll. Finally, in order to use the library in c# application, I have to include a reference to both of these dlls.

Is this the correct way to get it working? I was thinking probably there should be a way to simplify the process.

Can someone please help me with this question?

like image 230
Batul Avatar asked Jun 02 '10 14:06

Batul


People also ask

Can C call C++ library?

Oracle Developer Studio C and C++ use the same C runtime libraries, as noted in the section about compatible compilers. Using Oracle Developer Studio compilers, you can therefore use Standard I/O functions freely in both C and C++ code in the same program.

How do I combine C and C++?

You will need to wrap the C header file inclusion with the extern "C" { } as shown above. Then, you can just try to compile it (only the source file containing the main function) in a C++ compiler, and the rest of the C code with the C compiler, and then link the whole thing together.


1 Answers

Given that you're using a C++ library, I'm assuming it takes advantage of C++ semantics like classes, rather than just exposing procedures. If this is the case, then the way this is typically done is via a manually-created managed C++ interop library.

Basically, you create a managed C++ library in Visual Studio, reference your existing C++ library, and create a managed wrapper around your existing C++ classes. You then reference this (managed) C++ assembly in your C# project and include the original (unmanaged) C++ library in your C# assembly just as a file that gets placed in the build directory.

This is required because there is no way to reference things like C++ classes via P/Invoke (DllImport) calls.

If your base library is just a series of functions, then you can reference that directly in the C# project via P/Invoke functions.

Either way, all of the libraries mentioned above (for the first, the unmanaged C++ library, the managed C++ assembly, and the C# project, or, for the second, the unmanaced C++ library and the C# project) must be included in any project that references them. You cannot statically link the unmanaged library into the managed assembly.

like image 95
Adam Robinson Avatar answered Oct 27 '22 08:10

Adam Robinson