struct and pointer question in c#
-
Hi all ,Forgive my bad english,please. I'm new user in c#.I have one problem about struct and pointer. I want to create c# API that call DLL file in c++ . //DLL sample as below(c++): struct TESTA { DWORD A; WORD B; WORD C; BYTE D[16]; }; typedef TESTA* LPTESTA; BOOL CBook::InitialButton(LPTESTA pInfo) { //statement return true; } //C# code as below: unsafe public class callDLL { [StructLayout(LayoutKind.Sequential)] public struct TESTA { public int A; public ushort B; public ushort C; [MarshalAs(UnmanagedType.ByValArray, SizeConst= 16)] public byte[] D; } [DllImport("dllname.dll")] unsafe public static extern bool InitialButton(void* pInfo); } public class Initialize_sequence { unsafe static void Main(string[] args) { callDLL.TESTA pInfo=new callDLL.TESTA(); Console.WriteLine(Marshal.SizeOf(pInfo)); callDLL.InitialButton(&pInfo); //error happen :( } } error message show "Can't get position and size of Mananged type" Any one can provide idea for me ? Thanks. hello ALL..^^
-
Hi all ,Forgive my bad english,please. I'm new user in c#.I have one problem about struct and pointer. I want to create c# API that call DLL file in c++ . //DLL sample as below(c++): struct TESTA { DWORD A; WORD B; WORD C; BYTE D[16]; }; typedef TESTA* LPTESTA; BOOL CBook::InitialButton(LPTESTA pInfo) { //statement return true; } //C# code as below: unsafe public class callDLL { [StructLayout(LayoutKind.Sequential)] public struct TESTA { public int A; public ushort B; public ushort C; [MarshalAs(UnmanagedType.ByValArray, SizeConst= 16)] public byte[] D; } [DllImport("dllname.dll")] unsafe public static extern bool InitialButton(void* pInfo); } public class Initialize_sequence { unsafe static void Main(string[] args) { callDLL.TESTA pInfo=new callDLL.TESTA(); Console.WriteLine(Marshal.SizeOf(pInfo)); callDLL.InitialButton(&pInfo); //error happen :( } } error message show "Can't get position and size of Mananged type" Any one can provide idea for me ? Thanks. hello ALL..^^
Instead of using the "unsafe" keyword in C# and using void* in the extern function signature, try this:
public static extern bool InitialButton(ref TESTA pInfo);
and in the call to the function you would just docallDLL.InitialButton(ref pInfo);
The marshaller should automatically treat this as a pointer. -
Instead of using the "unsafe" keyword in C# and using void* in the extern function signature, try this:
public static extern bool InitialButton(ref TESTA pInfo);
and in the call to the function you would just docallDLL.InitialButton(ref pInfo);
The marshaller should automatically treat this as a pointer.