【问题标题】:Undeclared identifier error in managed code...Visual C#托管代码中未声明的标识符错误...Visual C#
【发布时间】:2014-07-12 13:53:36
【问题描述】:

我有一个使用 C++/CLI 代码的 C# 项目。我在 C++/CLI 中有一个名为 Main 的托管类,我有一个名为 codemain 的非托管类。在 C# 中,我创建了一个托管类的对象并使用它,但是当我运行我的项目时,我遇到了一些错误——其中大部分是:cm : undeclared identifier

我所有的代码都是seaCV 命名空间。当我在托管类 (Main) 之外的 seaCV 命名空间中定义 cm 对象时,我的项目运行没有错误,但是当我在托管类中定义 cm 时,我得到了那个错误。问题出在哪里?

seaCV.h 文件中我的托管班级:

#pragma once

#include <iostream>
#include "cv.h"
#include "cvaux.h"
#include "highgui.h"   

using namespace System;

namespace seaCV 
{     
    public ref class Main
    {
        public:
            codemain *cm;            
            Main();  
            ~Main();
            void initizalize(int x, int y, int x2, int y2, int tr_ind);    
    };
}

还有seaCV.cpp 文件:

#include "seaCV.h"
#include "codemain.h"

namespace seaCV
{
    void Main::initizalize (int x, int y, int x2, int y2, int trix) {       
        cm->init(x,y,x2,y2,trix);       
    }

    Main::Main() {
        cm=new codemain();    
    }

    Main::~Main() {
        delete cm;
        cm=0;
    }       
}

最后,我的非托管代码在codemain.h

#pragma once

#include "cv.h"
#include "cvaux.h"
#include "highgui.h"

namespace seaCV 
{
    public class codemain 
    {
    public:
        int xc,yc,xr,yr;

        codemain(void) {
            xc = xr = yc = yr = 1;
        }

        void init(int x, int y, int x2, int y2, int tracker_index) {
            xc = x;
            yc = y;
            xr = x2;
            yr = y2;
            ...
        }
    };
}

【问题讨论】:

    标签: c# class visual-studio-2012 c++-cli


    【解决方案1】:
    #include "seaCV.h"
    #include "codemain.h"
    

    那是你的问题。编译器将在您的 seaCV.h 文件中看到“codemain”,但不知道它的含义。您必须交换两个#include。

    请记住,C++ 编译器是单遍编译器,与 C# 编译器不同。它需要先查看标识符的定义,然后才能使用。

    您的代码中有几个小问题:

    • 声明原生 C++ 类 public 语法无效,删除 public
    • 你的 cm 变量应该是 private 以便 C# 代码看不到它
    • 您必须为 Main() 类编写一个终结器 !Main,这样当 C# 程序员忘记调用 Dispose() 时,您就不会泄漏内存。

    【讨论】:

      【解决方案2】:

      查看此链接以了解在 c# 中使用非托管代码:

      http://www.codeproject.com/Articles/1392/Using-Unmanaged-code-and-assembler-in-C

      【讨论】:

      • 请你解释一下为什么这会有所帮助
      • 主题涉及到在C#中使用非托管代码,上面没有提供。那部分代码可能会出错。上面的链接显示了在 C# 中使用非托管代码的正确方法,因此最好阅读并确定原因。
      • 站外链接没有什么价值。如果答案根本没有传达任何信息,那就是一个糟糕的答案。您可以将此作为评论。虽然这不是一个答案。您应该在答案中添加一些内容,或者转换为评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多