Marshal array of struct into PtrCreating a byte array from a streamHow do you convert a byte array to a hexadecimal string, and vice versa?Why are mutable structs “evil”?When to use struct?Calling GetGUIThreadInfo via P/InvokePassing a Structure to C++ API using Marshal.StructureToPtr in C#How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?All possible array initialization syntaxesHow to convert byte array to stringAccess Violation for Marshalling Ptr To Struct

Are there hydrocarbons on the Moon?

How to deal with my team leader who keeps calling me about project updates even though I am on leave for personal work?

Install specific version and arch, without specifying the release

What is a Heptagon Number™?

Pseudo Game of Cups in Python

What do these pins mean? Where should I plug them in?

Applications of mathematics in clinical setting

Is there any reason nowadays to use a neon indicator lamp instead of an LED?

Algorithm that spans orthogonal vectors: Python

How do rulers get rich from war?

Is there an in-universe reason Harry says this or is this simply a Rowling mistake?

Is it really necessary to have 4 hours meeting in Sprint planning?

Why do different vector<bool> elements share the same address?

Is the sentence "何でも忘れた" correct?

Was there a trial by combat between a man and a dog in medieval France?

How is the problem, G has no triangle in Logspace?

US entry with tourist visa but past alcohol arrest

I feel like most of my characters are the same, what can I do?

Cheap antenna for new HF HAM

What did the controller say during my approach to land (audio clip)?

Hiking with a mule or two?

What can a pilot do if an air traffic controller is incapacitated?

Can Northern Ireland's border issue be solved by repartition?

How is underwater propagation of sound possible?



Marshal array of struct into Ptr


Creating a byte array from a streamHow do you convert a byte array to a hexadecimal string, and vice versa?Why are mutable structs “evil”?When to use struct?Calling GetGUIThreadInfo via P/InvokePassing a Structure to C++ API using Marshal.StructureToPtr in C#How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?All possible array initialization syntaxesHow to convert byte array to stringAccess Violation for Marshalling Ptr To Struct






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I am calling a C library from a C# code. The function I am calling take as parameter a struct containing arrays of struct :



 struct Example1Struct

char* a;
uint16_t b;
AnotherStruct* c;



c here is an array of pointer to AnotherStruct.



the struct in my C# code look like this



public struct Example1Struct

public IntPtr StationName;//is char*
public UInt16 IdCode;
public IntPtr AnotherStruct; //array of struct AnotherStruct





public static IntPtr MarshalToPointer(object data)

Type valueType = data.GetType();
IntPtr buf = IntPtr.Zero;

if (valueType.IsArray)

if (data is char[])

var d = data as char[];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else if (data is char[,])

var d = data as char[,];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else

buf = Marshal.AllocHGlobal(Marshal.SizeOf(data.GetType().GetElementType()) * count);

long LongPtr = buf.ToInt64(); // Must work both on x86 and x64
for (int I = 0; I < data.Lenght; I++)

IntPtr RectPtr = new IntPtr(LongPtr);
Marshal.StructureToPtr(data[I], RectPtr, false); // You do not need to erase struct in this case
LongPtr += Marshal.SizeOf(typeof(Rect));




return buf;

else
buf = Marshal.AllocHGlobal(Marshal.SizeOf(data));
Marshal.StructureToPtr(data, buf, false);
return buf;



my problem here is that I cannot cast data (who is an array of AnotherStruct) to object[] , neither in IEnumerable. So I cannot access to data[I] and don't have data.Lenght



Any idea ?










share|improve this question



















  • 1





    Have you looked at applying the MarshalAs attribute to your structure instead? Let the marshaller deal with allocations, etc.

    – Damien_The_Unbeliever
    Mar 28 at 14:59

















1















I am calling a C library from a C# code. The function I am calling take as parameter a struct containing arrays of struct :



 struct Example1Struct

char* a;
uint16_t b;
AnotherStruct* c;



c here is an array of pointer to AnotherStruct.



the struct in my C# code look like this



public struct Example1Struct

public IntPtr StationName;//is char*
public UInt16 IdCode;
public IntPtr AnotherStruct; //array of struct AnotherStruct





public static IntPtr MarshalToPointer(object data)

Type valueType = data.GetType();
IntPtr buf = IntPtr.Zero;

if (valueType.IsArray)

if (data is char[])

var d = data as char[];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else if (data is char[,])

var d = data as char[,];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else

buf = Marshal.AllocHGlobal(Marshal.SizeOf(data.GetType().GetElementType()) * count);

long LongPtr = buf.ToInt64(); // Must work both on x86 and x64
for (int I = 0; I < data.Lenght; I++)

IntPtr RectPtr = new IntPtr(LongPtr);
Marshal.StructureToPtr(data[I], RectPtr, false); // You do not need to erase struct in this case
LongPtr += Marshal.SizeOf(typeof(Rect));




return buf;

else
buf = Marshal.AllocHGlobal(Marshal.SizeOf(data));
Marshal.StructureToPtr(data, buf, false);
return buf;



my problem here is that I cannot cast data (who is an array of AnotherStruct) to object[] , neither in IEnumerable. So I cannot access to data[I] and don't have data.Lenght



Any idea ?










share|improve this question



















  • 1





    Have you looked at applying the MarshalAs attribute to your structure instead? Let the marshaller deal with allocations, etc.

    – Damien_The_Unbeliever
    Mar 28 at 14:59













1












1








1








I am calling a C library from a C# code. The function I am calling take as parameter a struct containing arrays of struct :



 struct Example1Struct

char* a;
uint16_t b;
AnotherStruct* c;



c here is an array of pointer to AnotherStruct.



the struct in my C# code look like this



public struct Example1Struct

public IntPtr StationName;//is char*
public UInt16 IdCode;
public IntPtr AnotherStruct; //array of struct AnotherStruct





public static IntPtr MarshalToPointer(object data)

Type valueType = data.GetType();
IntPtr buf = IntPtr.Zero;

if (valueType.IsArray)

if (data is char[])

var d = data as char[];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else if (data is char[,])

var d = data as char[,];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else

buf = Marshal.AllocHGlobal(Marshal.SizeOf(data.GetType().GetElementType()) * count);

long LongPtr = buf.ToInt64(); // Must work both on x86 and x64
for (int I = 0; I < data.Lenght; I++)

IntPtr RectPtr = new IntPtr(LongPtr);
Marshal.StructureToPtr(data[I], RectPtr, false); // You do not need to erase struct in this case
LongPtr += Marshal.SizeOf(typeof(Rect));




return buf;

else
buf = Marshal.AllocHGlobal(Marshal.SizeOf(data));
Marshal.StructureToPtr(data, buf, false);
return buf;



my problem here is that I cannot cast data (who is an array of AnotherStruct) to object[] , neither in IEnumerable. So I cannot access to data[I] and don't have data.Lenght



Any idea ?










share|improve this question














I am calling a C library from a C# code. The function I am calling take as parameter a struct containing arrays of struct :



 struct Example1Struct

char* a;
uint16_t b;
AnotherStruct* c;



c here is an array of pointer to AnotherStruct.



the struct in my C# code look like this



public struct Example1Struct

public IntPtr StationName;//is char*
public UInt16 IdCode;
public IntPtr AnotherStruct; //array of struct AnotherStruct





public static IntPtr MarshalToPointer(object data)

Type valueType = data.GetType();
IntPtr buf = IntPtr.Zero;

if (valueType.IsArray)

if (data is char[])

var d = data as char[];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else if (data is char[,])

var d = data as char[,];
buf = Marshal.AllocHGlobal(Marshal.SizeOf(d.GetType().GetElementType()) * d.Length);

else

buf = Marshal.AllocHGlobal(Marshal.SizeOf(data.GetType().GetElementType()) * count);

long LongPtr = buf.ToInt64(); // Must work both on x86 and x64
for (int I = 0; I < data.Lenght; I++)

IntPtr RectPtr = new IntPtr(LongPtr);
Marshal.StructureToPtr(data[I], RectPtr, false); // You do not need to erase struct in this case
LongPtr += Marshal.SizeOf(typeof(Rect));




return buf;

else
buf = Marshal.AllocHGlobal(Marshal.SizeOf(data));
Marshal.StructureToPtr(data, buf, false);
return buf;



my problem here is that I cannot cast data (who is an array of AnotherStruct) to object[] , neither in IEnumerable. So I cannot access to data[I] and don't have data.Lenght



Any idea ?







c#






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 14:52









ilièsiliès

292 bronze badges




292 bronze badges










  • 1





    Have you looked at applying the MarshalAs attribute to your structure instead? Let the marshaller deal with allocations, etc.

    – Damien_The_Unbeliever
    Mar 28 at 14:59












  • 1





    Have you looked at applying the MarshalAs attribute to your structure instead? Let the marshaller deal with allocations, etc.

    – Damien_The_Unbeliever
    Mar 28 at 14:59







1




1





Have you looked at applying the MarshalAs attribute to your structure instead? Let the marshaller deal with allocations, etc.

– Damien_The_Unbeliever
Mar 28 at 14:59





Have you looked at applying the MarshalAs attribute to your structure instead? Let the marshaller deal with allocations, etc.

– Damien_The_Unbeliever
Mar 28 at 14:59












2 Answers
2






active

oldest

votes


















1
















Usually I'd recommend using the MarshalAs attribute rather than writing manual marshalling code. It looks like:



public struct Example1Struct

public IntPtr StationName;//is char*
public UInt16 IdCode;
public IntPtr AnotherStruct; //array of struct AnotherStruct



Could be:



public struct Example1Struct

[MarshalAs(UnmanagedType.LPStr)]
public string StationName;
public UInt16 IdCode;
[MarshalAs(UnmanagedType.LPArray)]
public AnotherStruct[] OtherStructs;



And the marshaller should do the right thing for you when you pass it to unmanaged code.






share|improve this answer

























  • [MarshalAs(UnmanagedType.LPArray)] give me this error at runtime : System.TypeLoadException: 'Cannot marshal field 'OtherStructs' of type 'AnotherStruct': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).'

    – iliès
    Apr 3 at 9:02



















0
















You can get the length of the array like this:



if (data is Array a) 
Console.WriteLine(a.Length);


Arrays in c# always derive from Array, so you can cast it to that.



But if possible in your real code, I'd recommend Damien's answer






share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55400602%2fmarshal-array-of-struct-into-ptr%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1
















    Usually I'd recommend using the MarshalAs attribute rather than writing manual marshalling code. It looks like:



    public struct Example1Struct

    public IntPtr StationName;//is char*
    public UInt16 IdCode;
    public IntPtr AnotherStruct; //array of struct AnotherStruct



    Could be:



    public struct Example1Struct

    [MarshalAs(UnmanagedType.LPStr)]
    public string StationName;
    public UInt16 IdCode;
    [MarshalAs(UnmanagedType.LPArray)]
    public AnotherStruct[] OtherStructs;



    And the marshaller should do the right thing for you when you pass it to unmanaged code.






    share|improve this answer

























    • [MarshalAs(UnmanagedType.LPArray)] give me this error at runtime : System.TypeLoadException: 'Cannot marshal field 'OtherStructs' of type 'AnotherStruct': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).'

      – iliès
      Apr 3 at 9:02
















    1
















    Usually I'd recommend using the MarshalAs attribute rather than writing manual marshalling code. It looks like:



    public struct Example1Struct

    public IntPtr StationName;//is char*
    public UInt16 IdCode;
    public IntPtr AnotherStruct; //array of struct AnotherStruct



    Could be:



    public struct Example1Struct

    [MarshalAs(UnmanagedType.LPStr)]
    public string StationName;
    public UInt16 IdCode;
    [MarshalAs(UnmanagedType.LPArray)]
    public AnotherStruct[] OtherStructs;



    And the marshaller should do the right thing for you when you pass it to unmanaged code.






    share|improve this answer

























    • [MarshalAs(UnmanagedType.LPArray)] give me this error at runtime : System.TypeLoadException: 'Cannot marshal field 'OtherStructs' of type 'AnotherStruct': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).'

      – iliès
      Apr 3 at 9:02














    1














    1










    1









    Usually I'd recommend using the MarshalAs attribute rather than writing manual marshalling code. It looks like:



    public struct Example1Struct

    public IntPtr StationName;//is char*
    public UInt16 IdCode;
    public IntPtr AnotherStruct; //array of struct AnotherStruct



    Could be:



    public struct Example1Struct

    [MarshalAs(UnmanagedType.LPStr)]
    public string StationName;
    public UInt16 IdCode;
    [MarshalAs(UnmanagedType.LPArray)]
    public AnotherStruct[] OtherStructs;



    And the marshaller should do the right thing for you when you pass it to unmanaged code.






    share|improve this answer













    Usually I'd recommend using the MarshalAs attribute rather than writing manual marshalling code. It looks like:



    public struct Example1Struct

    public IntPtr StationName;//is char*
    public UInt16 IdCode;
    public IntPtr AnotherStruct; //array of struct AnotherStruct



    Could be:



    public struct Example1Struct

    [MarshalAs(UnmanagedType.LPStr)]
    public string StationName;
    public UInt16 IdCode;
    [MarshalAs(UnmanagedType.LPArray)]
    public AnotherStruct[] OtherStructs;



    And the marshaller should do the right thing for you when you pass it to unmanaged code.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 28 at 15:05









    Damien_The_UnbelieverDamien_The_Unbeliever

    203k18 gold badges267 silver badges357 bronze badges




    203k18 gold badges267 silver badges357 bronze badges















    • [MarshalAs(UnmanagedType.LPArray)] give me this error at runtime : System.TypeLoadException: 'Cannot marshal field 'OtherStructs' of type 'AnotherStruct': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).'

      – iliès
      Apr 3 at 9:02


















    • [MarshalAs(UnmanagedType.LPArray)] give me this error at runtime : System.TypeLoadException: 'Cannot marshal field 'OtherStructs' of type 'AnotherStruct': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).'

      – iliès
      Apr 3 at 9:02

















    [MarshalAs(UnmanagedType.LPArray)] give me this error at runtime : System.TypeLoadException: 'Cannot marshal field 'OtherStructs' of type 'AnotherStruct': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).'

    – iliès
    Apr 3 at 9:02






    [MarshalAs(UnmanagedType.LPArray)] give me this error at runtime : System.TypeLoadException: 'Cannot marshal field 'OtherStructs' of type 'AnotherStruct': Invalid managed/unmanaged type combination (Array fields must be paired with ByValArray or SafeArray).'

    – iliès
    Apr 3 at 9:02














    0
















    You can get the length of the array like this:



    if (data is Array a) 
    Console.WriteLine(a.Length);


    Arrays in c# always derive from Array, so you can cast it to that.



    But if possible in your real code, I'd recommend Damien's answer






    share|improve this answer





























      0
















      You can get the length of the array like this:



      if (data is Array a) 
      Console.WriteLine(a.Length);


      Arrays in c# always derive from Array, so you can cast it to that.



      But if possible in your real code, I'd recommend Damien's answer






      share|improve this answer



























        0














        0










        0









        You can get the length of the array like this:



        if (data is Array a) 
        Console.WriteLine(a.Length);


        Arrays in c# always derive from Array, so you can cast it to that.



        But if possible in your real code, I'd recommend Damien's answer






        share|improve this answer













        You can get the length of the array like this:



        if (data is Array a) 
        Console.WriteLine(a.Length);


        Arrays in c# always derive from Array, so you can cast it to that.



        But if possible in your real code, I'd recommend Damien's answer







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 28 at 15:03









        René VogtRené Vogt

        35.6k13 gold badges52 silver badges72 bronze badges




        35.6k13 gold badges52 silver badges72 bronze badges































            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55400602%2fmarshal-array-of-struct-into-ptr%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript