C#DLL托管c++ (CLI) String^ 到 std::string 的相互转化

32 篇文章 0 订阅

当使用C++/CLI包装C++本地代码时,常常需要将System::String转换为std::string或者char*以调用native C++函数。.net环境中的字符串是unicode的,占2个字节,而很多native C++函数都没有考虑unicode,这种转换不仅仅是2字节转1字节,同时也涉及到字符集的转换。


#include "stdafx.h"  
#include <string>  
#include <msclr\marshal_cppstd.h>  
#include <iostream>  
  
using namespace msclr::interop;  
using namespace System;  
  
int main(array<System::String ^> ^args)  
{  
    // 为了可以打印wstring到控制台  
    std::wcout.imbue(std::locale("chs"));  
  
    // 声明两个string  
    std::string strOld = "阿里路亚!"; //std的string  
    String^ strNew = "耶稣基督!"; //cli的string.  
  
    //std::string转cli的string  
    String^ stdToCli = marshal_as<String^>(strOld);  
    Console::WriteLine(stdToCli);  
  
    //cli的string转std::string  
    std::string cliToStd = marshal_as<std::string>(strNew);  
    std::cout << cliToStd << std::endl;  
  
    //cli的string转std::wstring  
    std::wstring cliToWstring = marshal_as<std::wstring>(strNew);  
    std::wcout << cliToWstring << std::endl;  
}  


  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中调用 C++ DLL 函数的时候,如果函数的参数是 std::string 类型,需要进行一些特殊的处理。因为在 C++ 中,std::string 类型实际上是一个类,而在 C# 中没有对应的类型。 一种解决方案是,将 C++ 函数参数中的 std::string 类型改为 char* 类型,并且增加参数来指定字符串的长度。在 C# 中,可以使用 Marshal 类的各种方法来将字符串转换为 char* 类型,并将字符串的长度传递给 C++ 函数。 下面是一个示例代码,演示了如何在 C# 中调用一个 C++ DLL 函数,该函数的参数类型为 std::stringC++ DLL 函数的代码: ```c++ #include <string> #include <iostream> // 定义一个使用 std::string 作为参数的函数 void printString(std::string str) { std::cout << str << std::endl; } ``` 在 C# 中调用该函数的代码: ```c# using System; using System.Runtime.InteropServices; class Program { // 声明 C++ DLL 函数 [DllImport("MyCppLib.dll", CallingConvention = CallingConvention.Cdecl)] static extern void printString([MarshalAs(UnmanagedType.LPStr)] string str, int length); static void Main(string[] args) { // 要传递给 C++ DLL 函数的字符串 string myString = "Hello, world!"; // 将字符串转换为 char* 类型,并获取字符串的长度 byte[] strBytes = System.Text.Encoding.ASCII.GetBytes(myString); int strLength = strBytes.Length; // 调用 C++ DLL 函数 printString(myString, strLength); } } ``` 在 C# 中,使用 [MarshalAs(UnmanagedType.LPStr)] 特性将 C++ 函数参数中的 std::string 类型转换为 char* 类型,使用 System.Text.Encoding.ASCII.GetBytes() 方法将字符串转换为 byte[] 类型,并使用该数组的长度作为字符串的长度参数传递给 C++ 函数。 希望这个示例代码对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值