如何从.NET Core调用cygwin编译的C++?

Daa*_*aan 15 c# c++ cygwin cmake .net-core

我试图做同样的事情到这个:

我正在使用Windows,但我的目的是让我的代码在Linux上工作得太晚(因此我使用cygwin和clion for C++).VS2017使用普通的C#编译器为.NET Core应用程序编译C#.我的问题是在visual studio中出现此错误:

"该程序'[19944] dotnet.exe'已退出,代码为-1073741819(0xc0000005)'访问冲突'."

这是我的cmake文件(使用clion生成):

cmake_minimum_required(VERSION 3.10) project(callFromCsharp)

set(CMAKE_CXX_STANDARD 14)

add_library(callFromCsharp SHARED library.cpp)
Run Code Online (Sandbox Code Playgroud)

这是我在library.cpp中的C++代码:

#include <cstdint>

extern "C" __declspec(dllexport) int32_t Test(){
    return 10;
}
Run Code Online (Sandbox Code Playgroud)

这是我的clion生成的cmake调用

C:\ Users\Daant.CLion2018.1\system\cygwin_cmake\bin\cmake.exe --build/cygdrive/c/Users/Daant/CLionProjects/callFromCsharp/cmake-build-release --target callFromCsharp - -j 6

这是我的C#代码:

    class Program
    {
        [DllImport("cygcallFromCsharp.dll", EntryPoint = "Test", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
        public static extern Int32 Test();

        [STAThread]
        static void Main()
        {
            var res = Test();
            Console.WriteLine($"Done! {res}");
            Console.ReadLine();
        }
    }
Run Code Online (Sandbox Code Playgroud)

怎么解决这个?我只想调用一个没有错误或异常的C++方法.

SHR*_*SHR 5

让我们从不该做什么开始

当从 C# 加载 Cygwin dll 时(我猜从 Visual studio 中它会是相同的)。

  1. 不使用AnyCPU作为平台,更喜欢使用x64或x86平台,分别添加到Cygwin dll中。
  2. 由于某种原因,我还没有弄清楚为什么从 dll 调用sprintf, sscanf, stringstream... 和打印到控制台方法会导致程序停止。

现在你可以做什么:

  1. 确保 cygwin bin 文件夹添加到路径中,或者将 DLL 的依赖项复制到 DLL 的文件夹中(依赖项通常为:Cygwin1.dll、cyggcc_s-seh-1.dll cygstdc++-6.dll。使用Dependency Walker工具检查)。
  2. 只是为了确保:添加 EXPORT_API 宏,在每个导出的方法上使用它。喜欢:

#define EXPORT_API extern "C" __cdecl __declspec(dllexport)

  1. 您的 DLL 示例非常简单,使用 Cygwin 控制台编译您的代码: g++ -c library.cpp; g++ -o cygcallFromCsharp.dll library.o
  2. 我在 C# 中使用了以下内容(调试运行目录设置为 dll 位置):

DllImport(@"cygcallFromCsharp.dll", CallingConvention=CallingConvention.Cdecl)] static extern int Test();

希望它会有所帮助。