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

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현