开发者

C++ Cli [MarshalAs] attribute moment of taking effect?

开发者 https://www.devze.com 2023-02-20 14:27 出处:网络
if I declare a value Struct in C++ CLI in this way: [StructLayout(LayoutKind::Sequential, CharSet = CharSet::Ansi, Pack = 2)]

if I declare a value Struct in C++ CLI in this way:

  [StructLayout(LayoutKind::Sequential, CharSet = CharSet::Ansi, Pack = 2)]
  value struct TEST
  {
  public:
     UInt32 bla;                                 
     UInt32 foo;                                  
     [MarshalAs(UnmanagedType::ByValTStr, SizeConst = 10)]
     String^ somestring;
     UInt32 bar;                   
  };

and use that struct, when does the line [MarshalAs(UnmanagedType::ByValTStr, SizeConst = 10)] take effect? Has it only a effect if I call some native function which is declared with dll import or if I do manually marshalling or the whole time?

My question lead to a implementation of a C++ Cli Wrapper for Native C funct开发者_如何学运维ions for some C# modules in a large project. if I do something like this:

TEST bla;
pin_ptr<TEST> pinner=&bla;

Is it certain, that in that moment after pinning my struct is wrapped together and has a size of 22 Byte (3*4 for the integer and 10 for the string)? Or could the string be bigger?


Yes, it takes effect when you make a call to an unmanaged function that you've declared with the [DllImport] attribute and that function has an argument of type TEST. Or when you explicitly marshal the structure with Marshal::StructureToPtr or Marshal::PtrToStructure. It does not take effect in your 2nd snippet. Nor is it necessary to use pin_ptr<> there, the bla variable is stored on the stack so doesn't have to be pinned.

This is something you very rarely ever do in C++/CLI. Since you'd have the unmanaged version of TEST already available from a .h file. You'd simply create that unmanaged version and copy the members, lots faster than leaving it up to the pinvoke marshaller. But you can, at least it takes care of the string. Use Marshal::StructureToPtr().


I'll answer one part of your question: Using pin_ptr does not cause marshalling to occur. pin_ptr is locking down the address of the managed object--it is not marshalling it to an unmanaged object. See http://msdn.microsoft.com/en-us/library/1dz8byfh(v=vs.80).aspx for more details.


Use a fixed-size buffer instead: How do I specify a fixed-size buffer in C++/CLI?

0

精彩评论

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

关注公众号