开发者

Passing Structure from C++ CLI to Unmanaged Code

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜