从 C++ 传递结构CLI 到非托管代码
我有一个具有以下定义的非托管代码,
void Load(const somestruct& structinst)
{
//dosomething.
}
我想将一个结构从 CLI 传递到非托管代码中的此方法作为引用,并在 CLI 中取回该结构。
我尝试在 CLI 中创建一个结构 as
[StructLayout(LayoutKind::Sequential, CharSet = CharSet::Ansi, Pack = 2)]
ref struct TEST
{
[MarshalAs(UnmanagedType::SysInt)]
int k;
};
并尝试将结构传递为 as
CLIWrapperClass::WrapperMethod()
{
TEST test;
this->NativeClassInstance->Load(test);
}
并收到类似 error C2664: 'NativeClass::Load' : Cannot conversionparameter 1 from 'Namespace::WrapperClass::TEST' to 'NativeClass 的错误::somestruct&'
我将如何实现这一目标?
I have an unmanaged code that has the following definition,
void Load(const somestruct& structinst)
{
//dosomething.
}
I want to pass a structure from CLI to this method in the unmanaged code as a ref and get back the structure in CLI.
I tried creating a struct in CLI as
[StructLayout(LayoutKind::Sequential, CharSet = CharSet::Ansi, Pack = 2)]
ref struct TEST
{
[MarshalAs(UnmanagedType::SysInt)]
int k;
};
and tried passing the struct as
CLIWrapperClass::WrapperMethod()
{
TEST test;
this->NativeClassInstance->Load(test);
}
and am getting an error like error C2664: 'NativeClass::Load' : cannot convert parameter 1 from 'Namespace::WrapperClass::TEST' to 'NativeClass::somestruct&'
How would I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要接触 C# 中的
TEST
结构,请确保somestruct
和TEST
结构具有相同基元类型的相同成员相同的尺寸。如果没有,为什么还要使用
StructLayout
呢?只需在 C++/CLI 中使用somestruct
本身即可,如下所示:If you need to touch the
TEST
structure from C#, please make sure thatsomestruct
andTEST
structures have the same members of the same primitive type with the same size.If not, why bother with
StructLayout
? Just go and usesomestruct
itself in C++/CLI like:本机代码与垃圾收集器可以声音移动的 .net 类型不兼容。可以使用固定和铸件,但这很脆弱。更好的方法是将数据从托管类型复制到本机结构的实例,然后再复制回来。
native code is incompatible with .net types which can be moved sound by the garbage collector. it's possible to use pinning and a cast, but that's fragile. better is just to copy the data from the managed type to an instance of the native struct and back again.