G
Guest
I saw this article here:
http://www.arstdesign.com/articles/interopmarshaling.html
But i had some problems doing this.
Codes:
/* C Structure
typdef struct {
int avalue;
int bvalue;
unsigned char cvalue[10];
} TestA;
*/
// C# Structure
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct TestA
{
public const int strlength = 10;
public short avalue;
public short bvalue;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=strlength)]
public string cvalue;
}
/* C function
SOMEAPI int SOME_DECL Get_Details(int, TestA *);
*/
// My C# platform invocation - follow your article
[DllImport("Some3rdParty.dll", EntryPoint="#1", SetLastError=true,
ExactSpelling=true, CharSet=CharSet.Ansi)]
private static extern short Get_Details(short handle, IntPtr lpParam);
// The implementation based on the article
TestA myTestA = new TestA();
int result = 0;
int size = Marshal.SizeOf(typeof(TestA));
IntPtr pncmetrics = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(myTestA, pncmetrics, true);
// somehandle is a short handle global value get from other methods call
result = Get_Details(somehandle, pncmetrics);
Marshal.PtrToStructure(pncmetrics, myTestA); // this part, it break and i
receive an error, check below!
Marshal.FreeHGlobal(pncmetrics);
--Error------------------
An unhandled exception of type 'System.ArgumentException' occurred in
mscorlib.dll
Additional information: The structure must not be a value class.
http://www.arstdesign.com/articles/interopmarshaling.html
But i had some problems doing this.
Codes:
/* C Structure
typdef struct {
int avalue;
int bvalue;
unsigned char cvalue[10];
} TestA;
*/
// C# Structure
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct TestA
{
public const int strlength = 10;
public short avalue;
public short bvalue;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=strlength)]
public string cvalue;
}
/* C function
SOMEAPI int SOME_DECL Get_Details(int, TestA *);
*/
// My C# platform invocation - follow your article
[DllImport("Some3rdParty.dll", EntryPoint="#1", SetLastError=true,
ExactSpelling=true, CharSet=CharSet.Ansi)]
private static extern short Get_Details(short handle, IntPtr lpParam);
// The implementation based on the article
TestA myTestA = new TestA();
int result = 0;
int size = Marshal.SizeOf(typeof(TestA));
IntPtr pncmetrics = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(myTestA, pncmetrics, true);
// somehandle is a short handle global value get from other methods call
result = Get_Details(somehandle, pncmetrics);
Marshal.PtrToStructure(pncmetrics, myTestA); // this part, it break and i
receive an error, check below!
Marshal.FreeHGlobal(pncmetrics);
--Error------------------
An unhandled exception of type 'System.ArgumentException' occurred in
mscorlib.dll
Additional information: The structure must not be a value class.