Search code examples
c#c++interop

How do I use DLLImport with structs as parameters in C#?


All the examples I can find using DLLImport to call C++ code from C# passes ints back and forth. I can get those examples working just fine. The method I need call takes two structs as its import parameters, and I'm not exactly clear how I can make this work.

Here's what I've got to work with:

I own the C++ code, so I can make any changes/additions to it that I need to.

A third party application is going to load my DLL on startup and expects the DLLExport to be defined a certain way, so i can't really change the method signature thats getting exported.

The C# app I'm building is going to be used as a wrapper so i can integrate this C++ piece into some of our other applications, which are all written in C#.

The C++ method signature I need to call looks like this

DllExport int Calculate (const MathInputStuctType *input, 
    MathOutputStructType *output, void **formulaStorage)

And MathInputStructType is defined as the following

typedef struct MathInputStuctTypeS {
    int             _setData;
    double              _data[(int) FieldSize];
    int             _setTdData;
} MathInputStuctType;

Solution

  • The MSDN topic Passing Structures has a good introduction to passing structures to unmanaged code. You'll also want to look at Marshaling Data with Platform Invoke, and Marshaling Arrays of Types.