Ahmad
Ahmad

Reputation: 24927

How to call a C++ function from c#

I am trying to call a C++ function provided from a college in C#. He has provided me with a dll and the following header file.

C++ Header

#include "../libs/tfvo.h"

extern "C" __declspec(dllexport) vector<double> fvm(
            vector<double> yearFractions,   
            vector<double> discountFactors, 
            vector<double> weightings,      
            double alpha_meanReversion,     
            double sigma_meanReversion,     
            double alpha_shortRate,         
            double alpha_meanReversion,
            double sigma_shortRate,         
            vector<double> startingValues = vector<double>(3,0.01));

I am using the following C# code to call the above c++ function which results in the following error.

"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

How do I call this function in C#? Does the C++ code need to change?

C#

var result = SimpleDllTest.testWrapper(); // In a console app

class SimpleDllTest
{
    [DllImport("fvm.dll")]
    public static extern IntPtr fitVasicekModel(
        IntPtr yearFractions,
        IntPtr weightings,
        double alpha_meanReversion,     
        double sigma_meanReversion,     
        double alpha_shortRate,         
        double sigma_shortRate,
        IntPtr startingValues
        );


    public static double [] testWrapper()
    {

        var t = new double[] { 0.1, 1.2 };
        var v = new double[] { 0.1, 1.2 };

        int size = Marshal.SizeOf(t[0]) * t.Length;
        IntPtr pnt = Marshal.AllocHGlobal(size);
        Marshal.Copy(t, 0, pnt, t.Length);

        int sizev = Marshal.SizeOf(v[0]) * v.Length;
        IntPtr pntv = Marshal.AllocHGlobal(sizev);
        Marshal.Copy(v, 0, pntv, v.Length);

        IntPtr result = fitVasicekModel(pnt, pnt, 1, 1, 1, 1, pntv);
        try
        {
            return (double[])Marshal.PtrToStructure(result , typeof(double[]));
        }
        finally
        {
            // Free the pointer here if it's allocated memory
        }
    }
}           

More background: My college has develop several financially related calculations and I am hoping with minimal effort we can reuse his entire library in another C# application. Both he an I have very minimal experience in this area (creating exportable C++ code and using it in C#) so any other tips etc will be welcomed.

Upvotes: 0

Views: 448

Answers (2)

Sean
Sean

Reputation: 62532

You've got no chance of calling this function directly from C#. A vector<> has no relation to a C# int[].

Your best bet would be to wrap the C# library in a manged C++ wrapper so that you can do the translation from the C# types to the C++ types on the way in, and the mapping from the C++ types to the C# types on the way out.

Upvotes: 1

Ricibob
Ricibob

Reputation: 7725

If you working with the developer of the library (as aposed to just using his lib) it might be worth looking at him providing a C++CLI build that you can work with directly with standard C#. You would need to deal with the vector/stl use in lib code - either replace this with cli Lists (or other managed containers) or find a wrapper solution (There are various SO posts about eg here and here).
I think that is likely going to be easier long term solution than pinvoke based interop to raw C++.

Upvotes: 0

Related Questions