首页 > 解决方案 > 从 .Net DLL 引用方法时,C++ 函数的 Ruby FFI 调用在脚本执行时失败

问题描述

我已经在 ffi github 上打开了一个问题,但我也在这里发帖,因为显然堆栈溢出具有更广泛的社区。或许你们会有一些想法。

我有以下戏剧性的故事要与您分享:

  1. 我需要从 ruby​​ 进程访问 .Net dll。
  2. 在这种情况下,COM 不是一个选项,请认为这是理所当然的 :)
  3. 我已经在 .Net dll 上编写了一个 C++ 包装器 dll 并导出了所需的函数。
  4. 以下是简短的来源:

demo.cs - CSharpDemo.dll

...
    public class CSharpClass
    {
        public static string CSharpTest(string input)
        {
            return "Hello from C#";
        }
    }

demo.h - CppDemo.dll

...
extern "C" __declspec(dllexport) const char * CppTest(const char * inputValue);

demo_csharp.h - CppDemo.dll

...
using namespace CSharp::Demo;

inline
std::string CSharpTest(const char * inputValue) {
    String^ managedInput = ToManagedString(inputValue); // unmanaged input str to managed str

    String^ managedOutput = CSharpClass::CSharpTest(managedInput); // call C# method

    return ToStdString(managedOutput); // managed str to unmanaged str
}

demo.cpp - CppDemo.dll

...
const char * CppTest(const char * inputValue) {
    std::string output = CSharpTest(inputValue);
    char * str = _strdup(output.c_str());
    return str;
}

演示.rb

require "ffi"

module CppDemo
    extend FFI::Library
    
    ffi_lib "C:/full_path/CppDemo.dll", "C:/full_path/CSharpDemo.dll"
    
    attach_function :CppTest, [ :string ], :string
end

message = CppDemo.CppTest("input")
puts "message = #{message}"
  1. 它可以正常工作:
  1. 但是,只要 ffi 从 ruby​​ 脚本加载的 C++ dll 调用 .Net dll 方法 - 我就会收到以下错误: Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'CSharp.Demo, Version=1.0.0.0 , Culture=neutral, PublicKeyToken=null' 或其依赖项之一。该系统找不到指定的文件。在 CSharpTest(basic_string<char,std::char_traits,std::allocator >* , SByte* inputValue) 在 CppTest(SByte* inputValue) 在 c:\full_path\demo.cpp:line 5

  2. 问题:

我知道这篇文章可能有点长而且令人困惑,所以如果需要一些澄清,请告诉我。

任何反馈将不胜感激。

提前致谢!

标签: c#c++rubydllffi

解决方案


推荐阅读