简体   繁体   中英

Marshall array in C++ struct in C# struct

I am having a struct defined in C++ which contains int and std::string arrays which is a native C++ code (dll). I have used following method to get it in C#:

public class PInvokeData
{
    [StructLayout(LayoutKind.Sequential)]        
    public struct pinvoke_call
    {
        //[MarshalAs(UnmanagedType.LPArray,SizeConst=5,SizeParamIndex=0,MarshalType="int")]
        [MarshalAs(UnmanagedType.ByValArray, SizeConst=5)]//,SizeParamIndex =0,SafeArraySubType = VarEnum.VT_I4)]
        public int[] mynum;
    }
    [DllImport("DLL_pinvoke_base.dll")]
    public extern static pinvoke_call TestPInvoke();
}

the code compiles well. when i call this static method and get return value of struct from C++ and assign to another struct object in C# like

input = PInvokeData.TestPInvoke();

i get exception of MarshalDirectiveException was unhandeled. Method's type signature is not PInvoke compatible. I tryed to solve the problem via other forum threads, but i did not get the result.

the struct in C++ code is same as there shown for C# struct like

struct pinvoke_call
{
    int mynum[5]
};

After calling a function C++ it returns this structure variable from there to C# which i want to marshal

Thanks for reply, Ashutosh

There are some restrictions in the CLR in what kind of structs may be used as a return type in a PInvoke call. I'm not sure it supports array members.

Also, the CLR does not support marshaling std:strings. You'll have to write some C++ code to return that in a more CLR-friendly way (such as an output LPSTR parameter).

after long time im replying sorry for that, since i almost forgot, i got solution for this. I returned struct pointer from C++ function TestPInvoke() and then used IntPtr to receive that pointer as void pointer and then used Marshal.PtrToStruct() function to map it into C# struct. Thanks for all your support guys...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM