我尝试按照以下步骤操作:Calling C# from C++, Reverse P/Invoke, Mixed Mode DLLs and C++/CLI 1.我制作名为TestLib的C# Dll:
namespace TestLib
{
public class TestClass
{
public float Add(float a, float b)
{
return a + b;
}
}
}
2.然后,我创建名为 WrapperLib 的 C++/CLI Dll 并添加对 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. 为了检查这个示例,我创建了 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;
}
但是我遇到了一些错误:
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
好吧,我知道我错过了某个地方,但是在哪里?
最佳答案
根据@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;
}
如果您不包含包装器库的头文件,C++ 编译器将永远找不到它的函数,并且您将不断收到之前显示的错误。
关于c# - 从 native C++ 或 C 调用 C# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11120750/