从本机C+调用C#函数+;或C

从本机C+调用C#函数+;或C,c#,c++-cli,pinvoke,C#,C++ Cli,Pinvoke,我将尝试按照以下步骤操作: 1.我将C#Dll命名为TestLib: namespace TestLib { public class TestClass { public float Add(float a, float b) { return a + b; } } } 二,。然后创建名为WrapperLib的C++/CLI Dll,并添加对C#TestLib的引用 C+ 3.例如,我创建了C++

我将尝试按照以下步骤操作: 1.我将C#Dll命名为TestLib:

namespace TestLib
{
    public class TestClass
    {
        public float Add(float a, float b)
        {
            return a + b;
        }
    }
}
二,。然后创建名为WrapperLib的C++/CLI Dll,并添加对C#TestLib的引用

C+ 3.例如,我创建了C++/CLI控制台应用程序,并尝试调用以下代码:

// 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;
}

<>我知道我在哪里漏掉了,但是在哪里?

这不是好的C++,看起来像java或者c*.< /p> 在C++/CLI中创建新对象的正确语法是

WrapperClass cl1;


C++具有堆栈语义,您必须告诉编译器您想要的是在函数末尾自动释放的本地对象(第一个选项),还是可以使用更长时间的句柄(第二个选项,使用
^
gcnew
).

根据@Ben Voigt的建议,我认为您的代码应该是这样的:

// 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;
}
//ConsoleTest.cpp:主项目文件。
#包括“stdafx.h”
#包括“WrapperLib.h”
使用名称空间系统;
使用名称空间包装库;
int main(数组^args)
{
浮动结果;
控制台::WriteLine(L“Hello World”);
包装类cl1;
结果=cl1。添加(1,1);
返回0;
}

如果你不包括你的包装库的头文件,C++编译器将永远找不到它的功能,你将继续得到你先前显示的错误。

如果编译器告诉你“嘿,有几个错误,请修理”你会先看哪里?请告诉我们哪些错误已修复。我已经添加了VS输出。如何从本地C++或C调用这个函数?我尝试使用WrPabPrime^ CL1= GCNeXWrPrPrimeCar();但是我得到了错误:错误1错误C2065:“WrapperClass”:未声明的标识符错误C2065:“cl1”:未声明的标识符错误C2061:语法错误:标识符“WrapperClass”@Superjet100:您还需要
#包括“WrapperLib.h”
,但在这个测试控制台应用程序中我没有#包括“WrapperLib.h”@Superjet100:Oh,这是一个单独的项目?然后添加一个引用,其中“代码> WrAPPIPLIB::WrapperClass < /code >。对于来自另一个DLL(类似WrapperClass)的原生类,要使它们在翻译单元中可见,必须包含它们的头文件(就像标准C++代码)。对于来自另一个dll的托管类,您只需要添加对项目的引用(就像在C中一样)。我的WrapperLib项目包含带有代码的WrapperLib.h和带有以下代码的WrapperLib.cpp:#include“stdafx.h”#include“WrapperLib.h”对吗?是的,我相信这是正确的,但是,您需要#将WrapperLib头文件包含到主项目中(用于测试它的项目)。正如上面提到的Mark Simith所说,在本机C++中,不管你做过还是没有引用过另一个项目,你仍然需要包括头文件。
WrapperClass cl1;
WrapperClass^ cl1 = gcnew WrapperClass();
// 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;
}