C# use of Unmanaged C Library, run time error when reading file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dantz
    New Member
    • Oct 2008
    • 71

    C# use of Unmanaged C Library, run time error when reading file

    Hi,

    I have an unmanaged C library that has calculation functions.
    The function has to open a binary file to get data reference.
    Then returns a "ReadError" or the result in a User defined structure

    Code:
    MyStruct Calculate(int itemid, int input1, int input2, double input3)
    {
    //initialize variable
    MyStruct *resultAns;
    double item1_result = 0;
    double item2_result = 0;
    double item3_result = 0;
    double item4_result = 0;
    double item5_result = 0;
    
    //allocate memory
    resultAns= (MyStruct*)malloc(sizeof(MyStruct));
    
    //open the file
    //read file and copy to buffer
    	/* Error happens here */
    
    //close the file
    //compute final values
    	resultAns->m_item1 = item1_result;
    	resultAns->m_item2 = item2_result;
    	resultAns->m_item3 = item3_result;
    	resultAns->m_item4	= item4_result;
    	resultAns->m_item5	= item5_result;
    
    return *resultAns;
    
    }
    
    struct myCalculatedItem
    {
    double m_item1;
    double m_item2;
    double m_item3;
    double m_item4;
    double m_item5;
    };
    typedef struct myCalculatedItem MyStruct;

    I already tried the C function in a console application using C++ and it is working correctly.
    But when I convert the C function into a DLL I don't get the same result. It just returns a "ReadError"

    Here is my C# equivalent:
    Code:
    [DllImport("TestLibrary.dll", EntryPoint = "CalAPI")]
    public static extern MyStruct Calculate(int itemid, int input1, int input2, double input3);
    
    [StructLayout(LayoutKind.Sequential)]
    public class MyStruct 
    {
            public double item1;
            public double item2;
            public double item3;
            public double item4;
    	public double item5;
    };
    I am not sure if I miss out something with some settings in P/Invoke or marshaling, so that it can call my C function properly.
    Please help.

    TIA

    -dantz
Working...