Accessing a C++ DLL with some pointers from a C# application

May 9 2008 9:58 AM
I've searched around and not found quite what I'm looking for so I'm really hoping that someone here can help me.

I need to access a DLL written in C++ from my c# desktop application. Whilst having a few years experience with c# and .NET i've absolutely no experience with C and pointers and memory allocation.

The dll is called UPTool.dll and the header file (and i presume the dll) contains this...

EXTERN int CALLTYPE CP( double * ranking, int Nobj, int Nalternatives , double * Y, double * w);

This is the function I'm trying to execute from my app. ranking, Y and w are all double vector arrays and i know their size. ranking gets written to in the function and is what i need to get back out of the function. As you can see ranking, Y and w are sent as pointers.

So i can set up a blank double[] ranking and populated double[] Y and double[] w and the two int's in the c# app no problem.

I need to call the DLL and from searching around it seems i need to use pinvoke and i got something like this - i believe the refs take care of the pointers but i'm not sure and to be honest even at this point I'm confused:

[DllImport("UPTool.dll", CharSet = CharSet.Auto)]
public static extern int CP(ref double[] ranking, ref int Nobj, ref int Nalternatives, ref double[] Y, ref double[] w);

To handle the inputs and outputs and any errors i then created another function that the application calls to run the DLL with the correct data:

public bool RunCP(int nscen, int natrib, double[] inputs, double[] weighting, out ArrayList CPRanking)
        {
            
            CPRanking = new ArrayList();

            try
            {
                double[] results = new double[nscen];

                CP(ref results, ref natrib, ref nscen, ref inputs, ref weighting);
                
                foreach (double result in results)
                {
                    CPRanking.Add(result);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

As you can imagine it didn't work and i receive the following error (when not using the try/catch) " AccessViolationException was unhandled - Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Not having any clues about C or tried anything like this before I'm now completely baffled! I'm also worried that even if it worked the garbage collector might move my memory anyway.

Answers (6)