使用来自 c++/cli 的 std::string 参数调用本机 c++ dll
Calling a native c++ dll with std::string argument from c++/cli
我有一个本机 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 *
个指针的包装函数。
我有一个本机 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 *
个指针的包装函数。