在C++中,我创建了此类:

public ref class UConfig
{
    public:
       UConfig(short nr);
       ~UConfig();
       bool checkNr();

    private:
      short _nr;
}

以及将在C#中调用的C++公共(public)类:
public ref class UConfigHandler
{
    public:
        UConfigHandler(UConfig^ uConfig);
}

然后在C#中,我可以这样做:
UConfig uConfig = new UConfig(1);
UConfigHandler uConfigHandler = UConfigHandler(uConfig);

在C++中,我对其进行调试,并在构造函数中进行调试:
UConfigHandler::UConfigHandler(UConfig^ uConfig)
{
    // while debugging I see that uConfig is: System::Object^
    // how to do the conversion from the uConfig to UConfig inside C++
    // I would like to do something like this but I got an exception
    UConfig myConfig = uConfig; // the program is stopped here but I dont know what is the error
}

因此,基本上我想将System::Object ^ uConfig转换为本地UConfig。我怎样才能做到这一点?

我用String ^做过的事情类似于string:


IntPtr stringPointer = (IntPtr)Marshal::StringToHGlobalAnsi(input);

string retrievedString = string((char*)stringPointer.ToPointer());

最佳答案

您正在尝试将UConfig实例的句柄分配给UConfig对象。您已将UConfig^ uConfig声明为引用,因此只能将其分配给引用。

如果这样做,这将等效于C++:

MyClass* mcp = new MyClass();
MyClass mcv = mcp;

换句话说,您的UConfigHandler构造函数应如下所示:
UConfigHandler::UConfigHandler(UConfig^ uConfig)
{
    UConfig^ myConfig = uConfig;
}

更新资料

您也许可以做到...可以封送struct,因此也应该封送class。我还没有这样做,但是Marshal.StructureToPtr的文档给出了一个类似的示例:
// Initialize unmanged memory to hold the struct.
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(uConfig));

// Copy the struct to unmanaged memory.
Marshal.StructureToPtr(uConfig, pnt, false);

// Create another UConfig.
UConfig myConfig ;

// Set this UConfig to the value of the
// UConfig in unmanaged memory.
myConfig = (UConfig)Marshal.PtrToStructure(pnt, typeof(UConfig));

但是,您将无法再利用垃圾回收:您已经分配了非托管内存,因此还必须释放它!如果您不释放分配的内存,则会发生内存泄漏,因此请不要大惊小怪:
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);

关于c# - 使用C++/CLI将对象从C#传递到C++或将Object ^转换为Object,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9910186/

10-09 09:09