从C#调用Cygwin编译的FLINT DLL时触发Access Violation错误
从C#调用Cygwin编译的FLINT库时触发Access Violation错误
我需要将为UNIX构建的FLINT库(用于快速整数乘法等数论运算)移植到Windows环境,再从C#应用中调用该库的功能。目前已通过Cygwin搭配GNU工具链成功编译FLINT库,且能在同样用Cygwin+GNU工具链编译的基础C++应用中正常调用,但尝试从C#调用封装后的DLL函数时,程序因Access Violation崩溃。
最初计划在Visual Studio中用MSVC(或Clang)构建C/C封装层并编译为DLL,方便直接管理C#端的调用,但用MSVC编译FLINT时遇到大量与GNU工具链专属宏相关的复杂错误,始终无法解决。因此改用Cygwin+GNU工具链在Visual Studio外构建了一个极简的C封装DLL,用来简化对FLINT单个函数的调用。
C++封装DLL头文件
#pragma once #define DllExport __declspec( dllexport ) #include <stdio.h> #include <string.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpz_factor.h" #include "fmpz_mpoly.h" #include "profiler.h" extern "C" { DllExport void FactorInteger_Alt(const char *str); DllExport int FactorIntegerDirect(int x); }
C#调用代码
using System.Runtime.InteropServices; using System.Text; namespace CsFlintApi { public class CsFlintApi { public static void IntegerFactorizationAlt(String str) { StringBuilder stringBuilder = new StringBuilder(str, 1000); IntFacAlt(stringBuilder); } public static void IntegerFactorizationDirect(int x) { int y = IntFacDirect(x); Console.WriteLine(y); } [DllImport("flintapi.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "FactorInteger_Alt")] internal static extern void IntFacAlt(StringBuilder stringBuilder); [DllImport("flintapi.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "FactorIntegerDirect")] internal static extern int IntFacDirect(int x); } }
两种调用方式均触发Access Violation错误。请问这是从C#调用Cygwin构建的DLL的根本性问题,还是存在其他原因?
另外需要说明:所有依赖DLL(libflint、flintapi、cygwin1、cygstdc++、cyggmp、cygmpfr、cyggcc_s-seh-1及kernel32)均直接放置在C#项目的bin文件夹中,这种做法是否正确?
编辑:已根据评论中的建议进行修改,但问题仍未解决。
内容的提问来源于stack exchange,提问作者nick.schachter
相关产品推荐
相关产品推荐

