Reputation: 233
I have created c dll and I want to call that c dll from FORTRAN f90 in visual studio 2019. Can anyone please help with a sample example.
I have tried the followed code.The code was build successfully, but while running, I GOT AN ERROR as displayed in the picture.
My fortran code
include 'MathLibrary.h'
program fortran
implicit none
print *, 'Max_size' , max_size
end program fortran
My MathLibrary.h
#pragma once
#ifndef EXT_MYLIB
#ifdef DLL_BUILD
#define EXT_MYLIB __declspec(dllexport)
#else
#define EXT_MYLIB __declspec(dllimport)
#endif // DLL_BUILD
#endif // !EXT_MYLIB
extern "C" int EXT_MYLIB max_size;
My MathLibrary.cpp
#include "pch.h"
#include "MathLibrary.h"
int EXT_MYLIB max_size = 100;
Upvotes: 1
Views: 790
Reputation: 7267
The reason for the error message is either that you have selected the wrong project type in Visual Studio for the DLL or that you incorrectly named the DLL as the "Command" on the Debugging property page for the project.
If you are using Intel Visual Fortran, which seems likely, there are at least two worked examples of calling a C DLL from Fortran in the Intel Parallel Studio XE for Windows Samples Bundle under MixedLanguage.
Including a C file doesn't work for Fortran, and including anything before the PROGRAM statement does nothing useful.
You are looking to reference a C variable from a DLL. That gets a bit more complicated. In Fortran, a C global variable is interoperable with a COMMON block or a module variable. It's a bit easier to do it as a COMMON block, even though that's now deprecated in the language:
program test
use, intrinsic :: ISO_C_BINDING
integer(C_INT) :: max_size
common /max_size/ max_size ! Same name, different entities
!DEC$ ATTRIBUTES DLLIMPORT :: /max_size/
print *, 'max_size', max_size
end
Or here's how to do it with a module variable. Note that you'll get a linker warning about a defined symbol being imported - you can ignore that:
module my_mod
use ISO_C_BINDING
integer(C_INT) :: max_size
bind(C,name="max_size") :: max_size
!DEC$ ATTRIBUTES DLLIMPORT :: max_size
end module my_mod
program test
use my_mod
print *, 'max_size', max_size
end
Your C DLL project needs to be separate from the Fortran executable project. They should be in the same Visual Studio solution and the Fortran project should depend on the C project (Right click on Fortran project and select Dependencies.) This will get the build order right, but because Visual C++ doesn't do output dependencies for DLL projects with non-C projects, you'll need to add the C project's .LIB as a source file for the Fortran project.
Upvotes: 1