How to define struct correctly in C# to use it over DllImported methods? RRS feed

  • Question

  • Hi everybody,
    I have an unmanaged C++ method I want to use in a C#-app, it's sig is:

    public extern static DmtxRegion dmtxDecodeFindNextRegion(DmtxDecode* decode);

    Somehow I don't manage to define the DmtxRegion-struct correctly, it looks as follows in C++:

    typedef struct DmtxRegion_struct {

    [some "simple" vars]

    DmtxMatrix3 raw2fit; /* THIS seems to be problematic */

    DmtxMatrix3 fit2raw; /* THIS seems to be problematic, too*/

    [some "simple" vars]

    } DmtxRegion;

    The part that makes problems is the DmtxMatrix, which is defined as:

    typedef double DmtxMatrix3[3][3];

    How can I define a two-dimensional array with fixed size in C#?
    I tried a lot, the last I came up with is:


    public struct DmtxRegion


    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.R8, SizeConst = 9)]

    public double[] raw2fit;

    [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.R8, SizeConst=9)]

    public double[] fit2raw;


    Still, I get a MarshalDirectiveException: Method's type signature is not PInvoke compatible.
    What can I do? I also tried to define the method differently so it returns an IntPtr, but then I get an AccessViolationException.

    Thanks for any advice, michael

    • Edited by michivo Thursday, June 19, 2008 7:26 PM reformatted
    Thursday, June 19, 2008 7:23 PM


  • The return value type of the function is a problem.  There is no standardized way in which compilers return structures by value.  They typically let the caller pass a hidden pointer on the stack frame.  You'd have a fighting chance if it were a pointer to a structure.  But this particular one cannot be P/Invoked.  You'll need to write a wrapper DLL in the C++/CLI syntax to make it callable.  Even an unmanaged wrapper that changes the signature could work.
    Hans Passant.
    • Marked as answer by Bruno Yu Monday, June 23, 2008 6:19 AM
    Thursday, June 19, 2008 8:49 PM