C++ Dll导出类中暴露std::string 等类型时爆出“warning C4251”警告的处理

C++ 在编写Dll时需要导出类给外部调用,如果在导出类中出现std::string或其他STL类型,通常会爆出下面的warning

简单的导出类定义如下:

class __declspec(dllexport) TestDll
{
public:
    TestDll(const char* data);
    ~TestDll();
    void test();
private:
    std::string m_str;
};
编译,出现下面警告:
warning C4251: “TestDll::m_str”: class“std::basic_string<char,std::char_traits<char>,std::allocator<char>>”需要有 dll 接口由 class“TestDll”的客户端使用

在定义导出类前先声明导出对应的模板类型:

template class __declspec(dllexport) std::basic_string<char, std::char_traits<char>, std::allocator<char>>;

不过,如果有其他导出类也有同样的声明的话,会出现重复定义的问题。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 C# 中调用 C++ DLL 中的函数入参为 `std::string` 类型的方法,需要使用 `MarshalAs` 特性将 C# 字符串转换为 C++ 字符串,并将其传递给 DLL 导出函数。以下是一个示例: C++ DLL 中的函数: ```cpp #include <string> extern "C" { __declspec(dllexport) void MyDllFunction(const std::string& str) { std::string msg = "Hello " + str + " from C++!"; printf("%s\n", msg.c_str()); } } ``` C# 代码: ```csharp using System; using System.Runtime.InteropServices; class Program { [DllImport("MyCppDll.dll")] public static extern void MyDllFunction([MarshalAs(UnmanagedType.LPStr)] string str); static void Main() { string str = "World"; MyDllFunction(str); } } ``` 在上述代码中,我们首先声明了从 C++ DLL 中导入的函数 `MyDllFunction`,它接收一个 `std::string` 类型的参数。在 C# 中,我们需要使用 `MarshalAs` 特性将 C# 字符串转换为 C++ 字符串,并将其传递给 DLL 导出函数。 在调用 `MyDllFunction` ,我们直接传递一个 C# 字符串给它,因为 C# 字符串和 C++ `std::string` 类型可以自动转换。在 C# 中,字符串默认使用 Unicode 编码,而在 C++ 中,`std::string` 默认使用 ASCII 编码。因此,在使用 `MarshalAs` 特性,我们需要指定字符串的编码格式为 `UnmanagedType.LPStr`,以确保 C# 字符串能够正确地转换为 C++ 字符串。 需要注意的是,如果 C++ DLL 中的函数接收的是一个指向 `std::string` 对象的指针或引用,而不是直接接收 `std::string` 对象,则需要使用 `IntPtr` 类型来传递指针或引用。在这种情况下,我们需要使用 `Marshal.StringToHGlobalAnsi` 方法将 C# 字符串转换为指向 ANSI 字符串的指针,并在调用完 DLL 导出函数后使用 `Marshal.FreeHGlobal` 方法释放内存。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值