Click here to Skip to main content
15,946,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to do an interop to a C# structure from C++.
The structure c#

public static IntPtr tempNode = IntPtr.Zero;

and also i am using Marshal.PtrToStructure, Marshal.PtrToStringAuto as per requirement.

now i am trying with 64bit compiled exe, the address shared from c++ to c# is correct, but the functions
Marshal.PtrToStructure, Marshal.PtrToStringAuto are shifting the data within the structure, and filling junk values.
out of 8 bytes, only 4 bytes are copied/correct.

What I have tried:

Node is an structure in my code

public struct NODE

        public ulong ullSector;
        public ulong ullSize;

        unsafe public NODE* pNext;
        unsafe public NODE* pChild;
        unsafe public NODE* pParent;

        public uint dwID;
        public uint dwSelfNum;
        public uint dwParentNum;

        public IntPtr pwcName;  //this variable belongs to WCHAR* in c++

        public ushort wCT;
        public ushort wAT;

        public byte bStatus;
        public byte bMarked;
        public byte bNameLength;
        public byte bIsThisRAWFolderFile;
        public IntPtr Path;

IntPtr tempNode = IntPtr.Zero;
NODE _dynamicNode = (NODE)Marshal.PtrToStructure(tempNode, typeof(NODE));

if i do like these it shifting the data within the structure, and filling junk values.
out of 8 bytes, only 4 bytes are copied

if run in 32 bit then there is no problem in 64 only having this issue.
Updated 6-Jun-21 2:24am
Richard MacCutchan 6-Jun-21 7:24am    
What is the NODE structure?
Fazil13 6-Jun-21 7:28am    
I updated my question with NODE structure

See the notes to the Example at Marshal.PtrToStructure Method (System.Runtime.InteropServices) | Microsoft Docs[^] concerning 64-bit.
Share this answer
The problem is a bit vague, sorry. However, I believe setting your CharSet attribute (auto), does not sound like it's working. Check out Marshal.SystemDefaultCharSize (If 2 then Unicode, otherwise Ascii), try CharSet=Unicode on the attribute, or CharSet=Ascii.

Also, the layout of your struct could potentially be a problem, or not specifying the layout.

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct MyStruct

Link: StructLayoutAttribute Class (System.Runtime.InteropServices) | Microsoft Learn[^]
Share this answer
Richard Deeming 7-Feb-23 4:36am    
Hopefully the OP will have solved the problem some time in the last eighteen months. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900