Skip to main content
 首页 » 编程设计

c#之用 C++/CLI 包装 C++ 结构并从 C# 使用它

2024年02月06日11shanyou

我知道已经有很多类似的问题,但我无法解决我的问题。

我用 Visual C++ 编写了这段小代码

#pragma once 
 
using namespace System; 
 
namespace MyWrapper { 
public ref class MySubClass{ 
        String^ username; 
        String^ password; 
    }; 
 
public enum class MyEnum{ 
        VALUE1 = 1, 
        VALUE2 = 2, 
        VALUE3 = 3, 
        VALUE4 = 4 
    }; 
 
public ref class MyClass{ 
        String^ string1; 
        String^ string2; 
        String^ string3; 
        long exampleNumber; 
        MyEnum choosenValue; 
        MySubClass credentials; 
        unsigned int otherNumber; 
 
    }; 
} 

MyClass 是一个在外部 dll 中使用的结构,我是在查看 dll 的源代码时写的。它可以编译,我可以从我的 C# 代码中看到它,这个 C# 代码有效:

MyClass instance = new MyClass(); 

但这行不通:

instance.string1 = "test"; 

它无法在 MyClass 中找到 string1。 string1 只是一个例子,我看不到我需要的任何值。我做错了什么?

请您参考如下方法:

默认情况下,类的成员是私有(private)的。您需要将它们声明为公开。

public ref class MyClass  
{ 
public: 
    String^ string1; 
    String^ string2; 
    String^ string3; 
    long exampleNumber; 
    MyEnum choosenValue; 
    MySubClass credentials; 
    unsigned int otherNumber; 
}; 

如果您包装的结构是纯数据容器,那么使用ref struct 可能比ref class 更方便。默认情况下,ref struct 的成员具有public 可访问性。


根据评论,您现在遇到了 credentials 问题,这是您代码中的一个 ref class。就我个人而言,我倾向于对这两种结构使用 ref struct。然后使用属性公开包含的结构可能是最简单的:

public ref struct MySubClass 
{ 
    String^ username; 
}; 
 
public ref struct MyClass  
{ 
private: 
    MySubClass credentials; 
public: 
    property String^ username { 
        String^ get() 
        { 
            return credentials.username; 
        } 
        void set(String^ value) 
        { 
            credentials.username = value; 
        } 
    } 
};