使用 c++/cli 中的 std::string 参数调用本机 c++ dll

Calling a native c++ dll with std::string argument from c++/cli

本文关键字:c++ 参数 调用 本机 dll string std cli 中的 使用      更新时间:2023-10-16

我有一个本机的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 接口中使用std::string或任何编译器特定类型。

我想这就是你使函数extern "C"的原因。如果它没有extern "C"就不起作用,它很可能不起作用(因为不同的重整规则,这意味着不同的编译器或至少不同的std::string定义)。

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