c# - 从 native C++ 或 C 调用 C# 函数

标签 c# c++-cli pinvoke

我尝试按照以下步骤操作: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/

相关文章:

c# - 在 .NET Web 应用程序中使用 C 库

c# - Linq2Sql 数据上下文登录/注销行为

c# - .net 4.0 中返回 xml 而不是 json 的 asmx web 服务

c# - 为什么即使我释放/处置位图,我也会收到 OutOfMemoryException?

C++/CLI - URL 下载到文件

c# - 如何通过引用将 float 从 C++ 传递回 C#?

C# 移动扫描仪值表现得很奇怪

mysql - C++ .net float 到 System::String^

c# - pinvoke 编码 double 类型的二维多维数组作为 C# 和 C++ 之间的输入和输出

C# 到 C 代码 P/INvoke 多个标准 :string declarations lead to stack corruption