将struct handle从managed转换为非托管C ++ / CLI [英] convert struct handle from managed into unmanaged C++/CLI

查看:250
本文介绍了将struct handle从managed转换为非托管C ++ / CLI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我定义了一个结构:

In C#, I defined a struct:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct MyObject
{
   [MarshalAs(UnmanagedType.LPWStr)]
   public string var1;    

   [MarshalAs(UnmanagedType.LPWStr)]
   public string  var2;    
};

我在C ++中有这个结构:

I have this struct in C++:

public value struct MyObject
{
    LPWSTR var1;    
    LPWSTR var2;    
};

在C ++的方法中,这是一个从C#调用的公共类:

And in the method of C++ which is a public class to be called from C#:

TestingObject(MyObject^ configObject)
{
   // convert configObject from managed to unmanaged.
}

对象被正确调试,可以看到两个字符串var1和var2。然而,现在的问题是,我需要编组对象: configObject 到一个非托管对象。

The object is debugged correctly that I can see two strings var1 and var2. However, the problem now is that I need to marshal the object: configObject into an unmanaged object.

想到的是这样做:

TestingObject(MyObject^ configObject)
{
   // convert configObject from managed to unmanaged.
   MyObject unmanagedObj = (MyObject)Marshal::PtrToStructure(configObject, MyObject);  
}

这是我能想到的,但是当然,

That is what I can think of but off course, I got this error:


错误2错误C2275:'MyObject':非法将此类型用作
表达式

Error 2 error C2275: 'MyObject' : illegal use of this type as an expression

将托管对象转换为非托管对象是正确的吗?如果是,我如何能够正确地 Marshal :: PtrToStructure

Is that right to convert the managed object into unmanaged object? if yes, how can I can that Marshal::PtrToStructure correctly?

如果没有,你能提供给我正确的方式?

IF no, could you please provide me a correct way?

提前感谢。

推荐答案

Marshal :: PtrToStructure 它将非托管指针转换为托管对象。您希望 Marshal :: StructureToPtr

Marshal::PtrToStructure does the opposite of what you want, it converts an unmanaged pointer to a managed object. You want Marshal::StructureToPtr.

此外,您需要定义一个非托管类,因为MyObject是一个托管类型。假设你这样做了,你可以这样做(只是从C#示例转换而来):

Also, you would need to define an unmanaged class, because MyObject is a Managed Type. Assuming you have done that, you could do it like this (just converted this from the C# sample):

IntPtr pnt = Marshal::AllocHGlobal(Marshal::SizeOf(configObject)); 
Marshal.StructureToPtr(configObject, pnt, false);

然后你有一个指向数据的指针,你可以 memcpy 或任何到您的原生结构中。

You then have a pointer to the data, which you can memcpy or whatever into your native struct.

但并将保持托管类型。如果你想要一个真正的非托管类型,你必须定义一个匹配托管结构。

But MyObject is and will stay a managed type. If you want a truly unmanaged type, you have to define one that matches the managed struct.

只是想知道,为什么在托管结构中使用非托管LPWSTR?

Just wondering, why are you using unmanaged LPWSTR in a managed struct?

这篇关于将struct handle从managed转换为非托管C ++ / CLI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆