Superjet100
Superjet100

Reputation: 129

Call C# function from native C++ or C

I'm try to follow this steps: Calling C# from C++, Reverse P/Invoke, Mixed Mode DLLs and C++/CLI 1. I make C# Dll named TestLib:

namespace TestLib
{
    public class TestClass
    {
        public float Add(float a, float b)
        {
            return a + b;
        }
    }
}

2. Then I create C++/CLI Dll named WrapperLib and add reference to C# TestLib.

// WrapperLib.h

#pragma once

using namespace System;
using namespace TestLib;

namespace WrapperLib {

    public class WrapperClass
    {
    float Add(float a, float b)
        {
        TestClass^ pInstance = gcnew TestClass();
        //pInstance
        // TODO: Add your methods for this class here.
        return pInstance->Add(a, b);
        }
    };
}

C+ 3. For check tis example I've create C++/CLI console application and try to call this code:

// ConsoleTest.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace WrapperLib;

int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");
    WrapperClass cl1 = new WrapperClass();

    return 0;
}

But I get a few errors:

error C2065: 'WrapperClass' : undeclared identifier C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp    11  1   ConsoleTest
error C2146: syntax error : missing ';' before identifier 'cl1' C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp    11  1   ConsoleTest
error C2065: 'cl1' : undeclared identifier  C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp    11  1   ConsoleTest
error C2061: syntax error : identifier 'WrapperClass'   C:\Projects\TestSolution\ConsoleTest\ConsoleTest.cpp    11  1   ConsoleTest

Well I know somewhere I missed, but where?

Upvotes: 2

Views: 2281

Answers (2)

Felipe
Felipe

Reputation: 7381

According to @Ben Voigt suggestion I believe that your code should look somewhat like this:

// ConsoleTest.cpp : main project file.

#include "stdafx.h"
#include "WrapperLib.h"

using namespace System;
using namespace WrapperLib;

int main(array<System::String ^> ^args)
{
    float result;
    Console::WriteLine(L"Hello World");
    WrapperClass cl1;

    result = cl1.Add(1, 1);

    return 0;
}

If you don't include the header file of your wrapper library, the C++ compiler will never find its functions and you will keep getting the errors that you displayed earlier.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283634

That's not good C++, looks like Java or C#.

The correct syntax to create a new object in C++/CLI is

WrapperClass cl1;

or

WrapperClass^ cl1 = gcnew WrapperClass();

C++ has stack semantics, you have to tell the compiler whether you want a local object that is automatically disposed at the end of the function (first option), or a handle that can live longer (second option, using ^ and gcnew).

Upvotes: 1

Related Questions