[Mono-devel-list] Calling Native C api - Marshalling issue.

Yogendra Thakur YogendraT at ami.com
Thu Jul 28 10:15:41 EDT 2005

I am getting problem while executing the c library function from C#.

Following is the equivalent code .

C Code :
 //This is the structure in C
 typedef struct MyDataType
       u_int    data1;
    u_int   data2;
 } MyData;

//This is the C function which is called by passing pointer to above
 function u_int DoSomeOperation(MyData* pData)
  return pData->data1 +pData->data2;

 C# Code  :
Following code shows how I am executing that call.

 using System;
 using System.Runtime.InteropServices;
 namespace Test
  //Define equivalent class to MyData structure
  public class CSMyData
   public UInt32 data1;
   public UInt32 data2;

  public class Test

   //Import the dll and define C function.
   [DllImport ("mylibrary.dll", EntryPoint="DoSomeOperation")]
   static extern Int32 OperateData( ref  CSMyData pData);
   //Other way of defining
   //static extern Int32 OperateData( [In,Out]  CSMyData pData);

   //main function for console application
   static void Main()
    UInt32 result = 0;
    CSMyData inData = new CSMyData();

    inData.data1 = 0xFFFF;
    inData.data2 = 0xFF;

    result = OperateData(ref inData);

    Console.WriteLine(" Addition = " result.ToString();



When I am printing value in the  C code side ,ie  in DoSomeOperation
function , the values are corrupted.

Please let me know what part is wrong.


More information about the Mono-devel-list mailing list