VS2019搭配iFort实现C#调用Fortran报E_ACCESSDENIED错误如何解决
C#调用Fortran代码问题排查与解决(VS2019 + Intel Fortran Compiler环境)
需要实现C#调用Fortran代码的功能,所用开发环境为Visual Studio 2019和Intel Fortran Compiler(iFort),以下为现有实现流程、报错信息及最终解决方案。
现有实现步骤
- 首先创建Fortran DLL项目,设置为Release x64模式,以下代码可正常编译:
module Fortran_DLL_Lib implicit none contains subroutine adder(a,b,x,y) !DEC$ ATTRIBUTES DLLEXPORT, ALIAS:'adder' :: adder !DEC$ ATTRIBUTES REFERENCE :: x,y implicit none integer, intent(in) :: a,b integer, intent(out) :: x,y y = a + b x = 2*a+3*b end subroutine end module
- 随后创建C#控制台应用,同样设置为Release x64模式,代码如下:
using System; using System.Runtime.InteropServices; namespace Call_Fortran_Dll_FromCS_Test { class Program { [DllImport("Fortran_DLL_Lib.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void adder(int a, int b, [Out] int x, [Out] int y); static void Main(string[] args) { int a = 4; int b = 3; int x = 0; int y = 0; Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(x); Console.WriteLine(y); adder(a, b, x, y); // 此处报错 Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(x); Console.WriteLine(y); Console.ReadKey(); } } }
运行报错信息
程序运行到调用Fortran函数的位置抛出异常,错误日志如下:
Exception thrown: 'System.DllNotFoundException' in Call_Fortran_Dll_FromCS_Test.dll An unhandled exception of type 'System.DllNotFoundException' occurred in Call_Fortran_Dll_FromCS_Test.dll Unable to load DLL 'Fortran_DLL_Lib.dll' or one of its dependencies: Access is denied. (0x80070005 (E_ACCESSDENIED))
已尝试操作与限制说明
- 已将编译生成的
Fortran_DLL_Lib.dll和Fortran_DLL_Lib.lib文件分别复制到C#项目根目录、可执行文件输出目录,问题未解决。 - 开发环境无管理员权限,无法安装Dependency Walker、修改系统环境变量等需要提权的操作,仅需先完成功能概念验证,后续对接带WPF GUI的C#项目,可接受非DLL的调用方案。
解决方案与验证结果
- 标准DLL调用方案修正:首先修正C#端P/Invoke的参数声明,输出参数需要添加
out修饰符,修改后的函数声明为:
[DllImport("Fortran_DLL_Lib.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void adder(int a, int b, out int x, out int y);
调用时对应改为adder(a, b, out x, out y);即可匹配Fortran端的参数传递规则。
- 受限环境替代方案:如果受设备权限限制无法加载DLL,可将Fortran代码编译为独立控制台可执行程序,C#端通过
Process类启动Fortran程序,通过标准输入输出传递参数和获取结果,无需加载DLL,适配无管理员权限的受限环境。 - 最终验证:上述DLL调用方案在无权限限制的普通设备上,可同时兼容.NET Framework和.NET Core环境正常运行;受限环境下的报错为公司用户账户策略限制DLL运行导致,与代码逻辑无关。
内容的提问来源于stack exchange,提问作者CoderJoe1991
相关产品推荐
相关产品推荐

