none
Marshaling arrays from C++ to C# RRS feed

Answers

  • It doesn't.  IntPtr is a raw memory pointer, not an array.  The marshaller simply passes it to the unmanaged code without doing anything at all.  After the call returns, you have to dig out the data written into that memory yourself with functions like Marshal.PtrToStructure().

    Hans Passant.
    Monday, June 22, 2009 4:20 PM
    Moderator
  • Apartments is a COM concept.  You can't make COM method calls with P/Invoke.

    Hans Passant.
    • Marked as answer by mpoleg Tuesday, June 23, 2009 9:16 AM
    Monday, June 22, 2009 5:06 PM
    Moderator

All replies

  • Properly written C++ COM code should use a SAFEARRAY so this is not an issue.  Other options are the MarshalAsAttribute.SizeConst attribute for fixed size arrays or MarshalAsAttribute.SizeParamIndex if the array size is passed as another argument.  If that cannot work either, you can indeed marshal the array yourself as demonstrated in the first link by declaring the argument as IntPtr.  ICustomMarshaler is yet another option.

    These are just generic hints.  Post your C++ method declaration if you want specific advice.

    Hans Passant.
    Monday, June 22, 2009 3:37 PM
    Moderator
  • Actually it would be interesting to know how the default marshaler estimates an array size through just IntPtr.

    As an example of C++ code we can consider function TestOutArrayOfStructs from PinvokeLib.dll at
    http://msdn.microsoft.com/en-us/library/aa720410(VS.71).aspx

    It is called in the example at
    http://msdn.microsoft.com/en-us/library/2k1k68kw(vs.71).aspx

    Monday, June 22, 2009 4:05 PM
  • It doesn't.  IntPtr is a raw memory pointer, not an array.  The marshaller simply passes it to the unmanaged code without doing anything at all.  After the call returns, you have to dig out the data written into that memory yourself with functions like Marshal.PtrToStructure().

    Hans Passant.
    Monday, June 22, 2009 4:20 PM
    Moderator
  • Thank you. It is getting clearer.

    Could you, please, say about what is happening when a caller and a callee
    of a method with IntPtr parameter are in different appartments.

    Can a marshaler try to copy something between them?
    Can a marshaler run into an exception?
    Is such a parameter thread-safe?
    Monday, June 22, 2009 4:56 PM
  • Apartments is a COM concept.  You can't make COM method calls with P/Invoke.

    Hans Passant.
    • Marked as answer by mpoleg Tuesday, June 23, 2009 9:16 AM
    Monday, June 22, 2009 5:06 PM
    Moderator