【问题标题】:C++ CLR Managed DLL containing template classes to be used in C#C++ CLR 托管 DLL 包含要在 C# 中使用的模板类
【发布时间】:2014-03-12 15:52:06
【问题描述】:

这是我的 dll 中的模板类之一:

template <class Type>
public ref class linkedList {
protected:
    nodeType<Type>^ head;
    nodeType<Type>^ tail;

public:
    linkedList();
    linkedList(const nodeType<Type>^newHead);

    nodeType<Type>^ getHead() { return head; }
    nodeType<Type>^ getTail() { return tail; }
    void push(const Type item);
    Type pop();

    bool isEmpty();

    void refreshTail();
    void print();
    void destroy();
    void appendToTail(nodeType<Type>^const newNode);
    ~linkedList();
};

这已经定义好了。但是,当我引用 dll 时,它的命名空间没有显示。 我尝试添加这样的非模板类:

    public ref class number{
private: int x;
public: void exFunction(int y){ x=y;}
};

然后出现命名空间。假设命名空间是“MP”,我使用“使用 MP;”在 C# 中。 通过这样做,我能够调用 exFunction 但不能调用其他模板类。如何调用模板类?

【问题讨论】:

  • 与本机 C++ 中的限制完全相同,模板没有太多在 .h 文件中声明的外部链接。对于您声明 public 的类来说,这是一个非常 坏主意,您将很难在运行时诊断 InvalidCastExceptions。并且完全无法用于 C# 代码。请避免重新发明轮子并改用 System::Collections::Generic::LinkedList。一个通用类。

标签: c# .net templates dll c++-cli


【解决方案1】:

在您的 C++/CLI dll 中,改用“通用”:

generic<class Type>
public ref class linkedList

对此进行一些澄清:C++/CLI 允许“模板”和“通用”-“模板”的工作方式类似于典型的本地 C++ 模板,而“通用”的工作方式类似于 C# 中的泛型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多