2

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?

1
  • There are a lot of things wrong. A ref struct is a class in managed code. You don't use marshaling attributes in C++/CLI, the language is designed to deal with that. But the real problem is that you just declared a managed type that's different from the unmanaged type. Compiler doesn't like that. Write a true wrapper. Commented Aug 16, 2011 at 22:43

2 Answers 2

0

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't downvote, but the statement "ref struct TEST is not recognized in C#. It is invalid." is wrong. ref struct is just a managed reference type that has public (instead of private) members by default; C# sees it absolutely no differently than a managed reference type declared ref class -- indeed, they compile to the exact same IL.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.