Call C# dll function from C++/CLI

Bogdan Stojanovic picture Bogdan Stojanovic · Jan 27, 2011 · Viewed 19.3k times · Source

I have a C# dll. The code is below:

public class Calculate
{
    public static  int GetResult(int arg1, int arg2)
    {
        return arg1 + arg2;
    }

    public static  string GetResult(string arg1, string arg2)
    {
        return arg1 + " " + arg2;
    }

    public static   float GetResult(float arg1, float arg2)
    {
        return arg1 + arg2;
    }

    public Calculate()
    {
    }
}

Now, I am planning to call this dll from C++ on this way.

[DllImport("CalculationC.dll",EntryPoint="Calculate", CallingConvention=CallingConvention::ThisCall)]
extern void Calculate();

[DllImport("CalculationC.dll",EntryPoint="GetResult", CallingConvention=CallingConvention::ThisCall)]
extern int GetResult(int arg1, int arg2);

Here is function where is called GetResult

private: System::Void CalculateResult(int arg1, int arg2)
{
    int rez=0;

    //Call C++ function from dll
    Calculate calculate=new Calculate();
    rez=GetResult(arg1,arg2);
}

I got the error : "syntax error : identifier 'Calculate'". Can someone help me with this terrible error?

Answer

santiagoIT picture santiagoIT · Jan 27, 2011

You must be using c++ CLI, otherwise you could not call DllImport. If that is the case you can just reference the c# dll.

In c++ CLI you can just do as follows:

using namespace Your::Namespace::Here;

#using <YourDll.dll>

YourManagedClass^ pInstance = gcnew YourManagedClass();

where 'YourManagedClass' is defined in the c# project with output assembly 'YourDll.dll'.

** EDIT ** Added your example.

This is how your example needs to look like in CLI (for clarity I am assuming that G etResult is not a static function, otherwise you would just call Calculate::GetResult(...)

private: System::Void CalculateResult(int arg1, int arg2)
{
    int rez=0;
    //Call C++ function from dll
    Calculate^ calculate= gcnew Calculate();
    rez=calculate->GetResult(arg1,arg2);   
}