.net for native dll - how to minimize the risk of runtime errors?

I am developing a C # application. Since I have some algorithms for filling in the least squares in C / C ++ that are too cumbersome, translate too, I made C ++ code in dll and then created a wrapper in C #.

In C # code, I defined a structure that is passed to unmanaged C ++ code as a pointer. The structure contains initial values ​​for the fitting functions and is also used to return fitting results.

It seems to me that you should define the structure in both managed and unmanaged code. However, someone using my source code in the future may decide to change the structure fields in a C # application, not realizing that they also need to change the structure in their own code. In the best case, this will lead to runtime errors (and lead to worse results in the worst case), but there will be no error messages telling the developer / end user what is wrong.

From my point of view, it is impossible to create a test in an unmanaged C ++ DLL that checks whether the structure contains the correct fields, but is it possible to return the DLL with the correct format structure in the C # shell?

Otherwise, how can we reduce the risk that some careless programmer will lead to runtime errors that are hard to detect in the future?

Code example:

//C++
struct InputOutputStruct {
    double a,b,c;
}

extern "C" __declspec(dllexport) void DoSomethingToStruct(InputOutputStruct* s)
{

// ... algorithm

}

//C#
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
    public struct InputOutputStruct {
        public double a,b,c;
    }

[DllImport("CpluplusDll.dll")]
    public static unsafe extern bool DoSomethingToStruct(InputOutputStruct* s);

class CSharpWrapper {
    static void Main(string[] args)
    {
        InputOutputStruct s = new InputOutputStruct();
        unsafe {
            InputOutpustruct* sPtr = &s;
            DoSomethingToStruct(sPtr);
            s = *sPtr;
        }
    }
}
+5
source share
2 answers

It seems to me that you should define the structure in both managed and unmanaged code.

Not true. This is what C ++ / CLI invented to facilitate interaction with C ++ and .NET.

+4
source

but is it possible to return the DLL structure of the correct format to the C # shell?

I don’t think so, because you always need to define structures on the C # side.

Here is a solution that may work (never tested):

  • Give each structure that shares a unique identifier on both sides (GUID, Macros)
  • ++, , # ++. .
  • ++ # GUID, . sizeof .

  • .
  • ++ ,
+1

All Articles