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;
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#
add a comment
|
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#
1
Have you looked at applying theMarshalAs
attribute to your structure instead? Let the marshaller deal with allocations, etc.
– Damien_The_Unbeliever
Mar 28 at 14:59
add a comment
|
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#
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#
c#
asked Mar 28 at 14:52
ilièsiliès
292 bronze badges
292 bronze badges
1
Have you looked at applying theMarshalAs
attribute to your structure instead? Let the marshaller deal with allocations, etc.
– Damien_The_Unbeliever
Mar 28 at 14:59
add a comment
|
1
Have you looked at applying theMarshalAs
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
add a comment
|
2 Answers
2
active
oldest
votes
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.
[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
add a comment
|
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
add a comment
|
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
[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
add a comment
|
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.
[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
add a comment
|
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.
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.
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
add a comment
|
[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
add a comment
|
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
add a comment
|
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
add a comment
|
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
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
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
add a comment
|
add a comment
|
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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