Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call unmanaged C++ code from C# using pinvoke

Tags:

dllimport

I have a unmanaged C++ dll for which I do not have access to code but have all methods declarations for.

Lets for simplicity say 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 simply want to call the add function from C++ in 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:

Unable to find an entry point named 'Add' in DLL 'C:\CPP and CSharp Project\UnmanagedNumeric\Debug\numeric.dll'.

I CAN NOT change C++ code. Have no idea what is going wrong. Appreciate your help.

like image 446
ilyaw77 Avatar asked Jun 13 '11 14:06

ilyaw77


2 Answers

Using PInvoke you can only call global functions exported from Dll. To use exported C++ classes, you need to write C++/CLI wrapper. This is C++/CLI Class Library project, which exposes pure .NET interface, internally it is linked to unmanaged C++ Dll, instantiates a class from this Dll and calls its methods.

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

like image 147
Alex F Avatar answered Oct 29 '22 10:10

Alex F


If you need to create a wrapper, take a look at swig.org. It will generate one for most high level language like C#.

I just came across this program a few minutes ago while working the same problem that you are.

like image 2
Anahnymous Avatar answered Oct 29 '22 10:10

Anahnymous