c++ - 使用 c++/cli 中的 std::string 参数调用 native c++ dll

标签 c++ c++-cli interop dllimport

我有一个 native c++ dll,我试图从 c++/cli 项目调用它。这是dll的功能

extern "C"
{
   int DLL_EXPORT Add(std::string s1, std::string s2, std::string s3)
   {
     [do stuff]
   }
}

这是 c++/cli 中的引用:

using namespace System::Runtime::InteropServices;
[DllImport("my_dll.dll")]
extern "C" int Add(std::string, std::string, std::string);

当我调用该函数时,我将 String^ 对象编码为 std::string:

Add(msclr::interop::marshal_as<std::string>(stringA),
            msclr::interop::marshal_as<std::string>(stringB),
            msclr::interop::marshal_as<std::string>(stringC));

调用 DLL 时出现访问冲突异常。

最佳答案

DLL和CLI是用同一个编译器编译的吗?通常,不同的编译器可能对 std::string 有不同的定义,这可能会导致错误。

因此我通常不建议在 DLL 接口(interface)中使用 std::string 或任何编译器特定类型。

我想这就是您创建函数 extern "C" 的原因。如果没有 extern "C" 就无法工作,那么它很可能无法工作(因为不同的 mangling 规则,这意味着不同的编译器或至少不同的 std::string 定义)。

在这种情况下,我更愿意创建一个包装函数,它采用 const char * 指针。

关于c++ - 使用 c++/cli 中的 std::string 参数调用 native c++ dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35464520/

相关文章:

c++ - NuiApi.h 在 Visual Studio 2012 DLL 项目中包含失败

c++ - ld 返回 1 退出状态

c++-cli - c++/cli 中的 gcroot

c++ - 从 c 调用 swift

visual-studio - 如何在 VS2005 中自动生成的互操作程序集中保留 COM DLL 版本?

c++ - 如何在 2 个进程之间共享 COM 对象?

c++ - std::shared_ptr 模板化与非模板化复制/移动构造函数

c# - 将 C# 字符串传递给 C++/CLI 不会在 CPP 程序中显示字符串值

.net - System.Transactions.Diagnostics.DiagnosticTrace 抛出 TypeInitializationException

java - 将 clojure vec 传递给 POSTGRES IN 语句(?)