从 C++ 传递结构CLI 到非托管代码

发布于 2024-11-29 22:52:07 字数 730 浏览 1 评论 0原文

我有一个具有以下定义的非托管代码,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

漆黑的白昼 2024-12-06 22:52:07

如果您需要接触 C# 中的 TEST 结构,请确保 somestructTEST 结构具有相同基元类型的相同成员相同的尺寸。

如果没有,为什么还要使用 StructLayout 呢?只需在 C++/CLI 中使用 somestruct 本身即可,如下所示:

CLIWrapperClass::WrapperMethod()
{
  somestruct test;
  this->NativeClassInstance->Load(test);
}

If you need to touch the TEST structure from C#, please make sure that somestruct and TEST structures have the same members of the same primitive type with the same size.

If not, why bother with StructLayout? Just go and use somestruct itself in C++/CLI like:

CLIWrapperClass::WrapperMethod()
{
  somestruct test;
  this->NativeClassInstance->Load(test);
}
携余温的黄昏 2024-12-06 22:52:07

本机代码与垃圾收集器可以声音移动的 .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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文