Calling unmanaged C ++ code from C # using pinvoke

I have an unmanaged C ++ dll for which I do not have access to the code, but have all the method declarations for.

Lets say for simplicity that .h looks like this:

#include <iostream> #ifndef NUMERIC_LIBRARY #define NUMERIC_LIBRARY class Numeric { public: Numeric(); int Add(int a, int b); ~Numeric(); }; #endif 

and method implementation in .cpp file

 int Numeric::Add(int a, int b) { return (a + b); } 

I just want to call the add function from C ++ to my C # code:

 namespace UnmanagedTester { class Program { [DllImport(@"C:\CPP and CSharp Project\UnmanagedNumeric\Debug\numeric.dll", EntryPoint = "Add")] public static extern int Add(int a, int b); static void Main(string[] args) { int sum = Add(2, 3); Console.WriteLine(sum); } } } 

After trying to execute, I have the following error:

Cannot find entry point named "Add" to DLL "C: \ CPP and CSharp Project \ UnmanagedNumeric \ Debug \ numeric.dll".

I can not change the code in C ++. I don’t know what is going on. Appreciate your help.

+6
source share
3 answers

Using PInvoke, you can call global functions only from Dll. To use exported C ++ classes, you need to write a C ++ / CLI shell. This is a C ++ / CLI class library project that provides a clean .NET interface within which it is associated with an unmanaged C ++ Dll, instantiates a class from this Dll, and calls its methods.

Edit: you can start with this: http://www.codeproject.com/KB/mcpp/quickcppcli.aspx#A8

+4
source

If you need to create a wrapper, see swig.org . It will generate one for most high-level languages ​​such as C #.

I just stumbled upon this program a few minutes ago, working with the same problem as you.

+2
source

To use a class from C ++ with C #, you will need a C ++ / CLi wrapper between them, as mentioned in previous answers. To do this, it is not very straightforward. Here is a link that will tell you how to do it at a high level: C ++ / CLI shell for native C ++ for use as a reference in C # .

If you are new to this (e.g. me), you may stumble upon 1) - the connecting part. To solve this problem, you can see how I did it (see My part of the question): Linking link errors from managed to unmanaged C ++, despite linking to a .lib file with exported characters

+2
source

Source: https://habr.com/ru/post/890413/


All Articles