【发布时间】:2016-09-12 16:52:11
【问题描述】:
我正在尝试构建一个 C++/CLR 包装器以从 C# .Net 应用程序内部调用我的 C++ 代码。
以下是遵循的步骤:
C++ 项目:
cppproject.h
#ifndef _CPPPROJECT_H
#define _CPPPROJECT_H
typedef enum {
SUCCESS,
ERROR
} StatusEnum;
namespace cppproject
{
class MyClass {
public:
MyClass();
virtual ~MyClass();
StatusEnum Test();
};
}
#endif
cppproject.cpp
#include "cppproject.h"
namespace cppproject {
MyClass::MyClass() {};
MyClass::~MyClass() {};
StatusEnum MyClass::Test()
{
return SUCCESS;
}
}
现在包装项目(C++/CLR 类型)将 C# 和 C++ 捆绑在一起:
wrapper.h
// wrapper.h
#pragma once
#include "cppproject.h"
using namespace System;
namespace wrapper {
public ref class Wrapper
{
public:
/*
* The wrapper class
*/
cppproject::MyClass* wrapper;
Wrapper();
~Wrapper();
StatusEnum Test();
};
}
wrapper.cpp
// This is the main DLL file.
#include "stdafx.h"
#include "wrapper.h"
namespace wrapper {
Wrapper::Wrapper()
{
wrapper = new cppproject::MyClass();
}
Wrapper::~Wrapper()
{
delete wrapper;
}
StatusEnum Wrapper::Test()
{
return wrapper->Test();
};
}
最后是我得到错误的 C# 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wrapper;
namespace netproject
{
/*
* Enums
*/
public enum StatusEnum {
SUCCESS,
ERROR
};
public partial class netproject
{
public const int MAX_REPORT_DATA_SIZE = 1024;
public wrapper.Wrapper wrapper;
public netproject() { wrapper = new wrapper.Wrapper(); }
~netproject() { wrapper = null; }
public StatusEnum Test()
{
var sts = wrapper.Test(); <<- ERROR
return (netproject.StatusEnum) sts;<<- ERROR
}
}
}
C#项目的编译器错误:
error CS0122: 'wrapper.Wrapper.Test()' is inaccessible due to its protection level
error CS0426: The type name 'StatusEnum' does not exist in the type 'netproject.netproject'
我无法理解。 Test 在包装器项目和 C++ 项目中都被定义为 public。并且StatusEnum在错误行上方的C#项目中也是公开的。
帮助了解这里发生了什么......
【问题讨论】:
-
您不能在 C# 程序中使用非托管枚举类型。您必须在 C++/CLI 代码中声明
public enum class。只需从 int 转换即可。 -
回复
netproject.netproject: Do not name a class the same as its namespace. -
谢谢汉斯,但请您详细说明或举个例子...我的包装器中没有枚举...。演员表在
(netproject.StatusEnum)的返回时间完成。 ..
标签: c# c++ .net c++-cli wrapper