Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
like image 894
Jonathan Beerhalter Avatar asked Mar 23 '09 18:03

Jonathan Beerhalter


2 Answers

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.

like image 111
Jim Mischel Avatar answered Oct 02 '22 03:10

Jim Mischel


From the declaration you posted, your C# code will look something like this:

[DllImport("mydll.dll")]
static extern int Calculate(ref MathInputStructType input,
    ref MathOutputStructType output, ref IntPtr formulaStorage);

Depending on the structure of MathInputStructType and MathOutputStructType in C++, you are going to have to attribute those structure declarations as well so that they marshal correctly.

like image 33
casperOne Avatar answered Oct 02 '22 03:10

casperOne