簡體   English   中英

用C ++ / CLI包裝C ++結構並從C#中使用它

[英]Wrap C++ struct with C++/CLI and use it from C#

我知道已經有很多類似的問題,但是我無法解決我的問題。

我用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只是一個例子,我看不到我需要的任何值。 我做錯了什么?

默認情況下,類的成員是私有的。 您需要聲明它們是公開的。

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;
        }
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM