Calling Fortran DLL in Matlab with the help of C++

284 Views Asked by At

I have a fortran code and want to run it in MATLAB (2019). I want to stick with silverfrost (64-bit) compiler (FTN95) to compile my initial fortran code. In order to find out how it works, I started with a simple code in Fortran: (multiply.f90)

double precision function Mul(nummer1, nummer2)
implicit none
double precision :: nummer1, nummer2
Mul = nummer1 * nummer2
end 

I compiled it as a dll data and used this dll in C++ to generate a C++ dll (64-bit) to use it in MATLAB. The C++ dll is generated in Visual Studio 2015. Here is my C++ code (Cppdll.cpp):

// Cppdll.cpp
//

#include "stdafx.h"
#include "Cppdll.h"

using namespace std;

typedef double(*FUNCPOINTER)(double &var1, double &var2);

    double DLLRes(double num1, double num2)
    {
        HINSTANCE hDLL;
        FUNCPOINTER myFuncPointer;
        double result = -999.99;

        hDLL = LoadLibrary(L"multiply.dll");

        if (hDLL != NULL)
        {
            myFuncPointer = (FUNCPOINTER)GetProcAddress(hDLL, "MUL");
            if (!myFuncPointer)
            {
                result = -999.999;
            }
            else
            {
                result = myFuncPointer(num1, num2);
            }
        }
        return result;
    }

and the corresponding header (Cppdll.h):

#pragma once

#ifdef __cplusplus
extern "C" {
#endif
    __declspec(dllexport) double DLLRes(double num1, double num2);
#ifdef __cplusplus
}
#endif

I put these dlls (multiply.dll and Cppdll.dll) in MATLAB path, and load the Cppdll in the program. By loading the dll, MATLAB does not complain, but as I call the dll function (e.g. calllib('Cppdll','DLLRes',2.1,5.23)), MATLAB crashes unexpectedly, i.e. it usually works at the beginning and the results are correct but after a while MATLAB crashes with/without an error message. The error messages (if shown) are different but they all complain about Silverfrost exception handler:

Error sample 1

Error sample 2

Error

I should also mention MATLAB gives me the following warning as I run [notfound,warnings] = loadlibrary('Cppdll.dll','Cppdll.h') command:

warnings =

    'Cppdll.h
     Unescaped left brace in regex is deprecated here (and will be fatal in Perl 5.30), passed through in regex; marked by <-- HERE in m/struct([^;,{(]*){ <-- HERE (.*?)\}([^;])*;/ at C:\Program Files\MATLAB\R2019a\toolbox\matlab\general\private\prototypes.pl line 912.
     Cppdll_thunk_pcwin64.c
        Bibliothek "Cppdll_thunk_pcwin64.lib" und Objekt "Cppdll_thunk_pcwin64.exp" werden erstellt.
     '

Where did I make a mistake and how this problem can be solved?

Thx in advance!

0

There are 0 best solutions below