【问题标题】:How to call to C++ code from C++/CLI code?如何从 C++/CLI 代码调用 C++ 代码?
【发布时间】:2013-07-01 07:29:00
【问题描述】:

我在 Visual Studio 2010 Professional 中创建了一个 C++/CLI (Visual C++) 项目。然后我在项目中添加了一个非常小的 C++ 类。以下是代码

#include <stdafx.h>
#include <iostream>

using namespace std;

    class Tester
    {

    public:
        Tester(){};

        void show()
        {
            cout << "OKOK..Printing" << endl;
        }

    };

现在,我将一个按钮拖放到自动构建的 GUI 表单中,我将要从该按钮调用上述代码。以下是按钮的代码。

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 Tester ^t = gcnew Tester();
                             //Test t; - giving errors as well

             }
    };

当我执行代码时,我得到以下错误

1>------ Build started: Project: testdamn, Configuration: Debug Win32 ------
1>Build started 7/1/2013 12:59:38 PM.
1>InitializeBuildStatus:
1>  Touching "Debug\testdamn.unsuccessfulbuild".
1>GenerateTargetFrameworkMonikerAttribute:
1>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
1>ClCompile:
1>  All outputs are up-to-date.
1>  Test.cpp
1>  testdamn.cpp
1>c:\users\yohan\documents\visual studio 2010\projects\testdamn\testdamn\Form1.h(79): error C2065: 'Tester' : undeclared identifier
1>c:\users\yohan\documents\visual studio 2010\projects\testdamn\testdamn\Form1.h(79): error C2065: 't' : undeclared identifier
1>c:\users\yohan\documents\visual studio 2010\projects\testdamn\testdamn\Form1.h(79): error C2061: syntax error : identifier 'Tester'
1>  Generating Code...
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.86
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我还注意到,当我从按钮中删除类调用时,程序构建良好。那么,如何从 C++/CLI 调用这些 C++ 类?

【问题讨论】:

  • 你有没有把#includeTester 类的头文件放到GUI 表单中?
  • @MarceloCantos:不,因为它没有头文件。这是必需的吗?
  • 是的。 GUI 代码需要查看Tester 类的定义。这就是它抱怨的原因:'Tester' : undeclared identifier。此外,您不能将其视为 .Net 类。 ^tgcnew 不起作用。
  • @MarceloCantos:太好了!十分感谢!在我完成我的最终项目之前,我真的很想得到你们所有人的帮助:)

标签: c++ .net visual-studio-2010 class visual-c++


【解决方案1】:

查看您收到的编译器错误:

1>c:\...\testdamn\Form1.h(79): error C2065: 'Tester' : undeclared identifier
1>c:\...\testdamn\Form1.h(79): error C2065: 't' : undeclared identifier
1>c:\...\testdamn\Form1.h(79): error C2061: syntax error : identifier 'Tester'

编译器告诉您它找不到任何名为 Tester 的类,因此无法使用它。

为了使用您的Tester 类,您需要在包含您的Form 类定义的文件中包含包含其定义的头文件。这与您必须包含 iostream 标头才能使用 std::cout 的方式相同。

但是一旦你解决了这个问题,你就会遇到另一个问题:你试图使用gcnew 来实例化Tester,这是一个非托管 类。 gcnew 旨在实例化托管 类,并从托管堆中分配内存。您想使用常规 C++ new 运算符来实例化常规 C++ 非托管类。一旦编译器能够看到Tester 类的定义,它就会注意到这种不匹配并产生另一个错误。

【讨论】:

  • 太棒了!十分感谢!我真的希望我能得到你们所有人的帮助,直到我完成我的最终项目:) 我将此标记为答案。感谢您指导我解决下一个可能的错误!
猜你喜欢
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
相关资源
最近更新 更多