【问题标题】:passing _bstr_t between c# and C++ /CLI在 c# 和 C++ /CLI 之间传递 _bstr_t
【发布时间】:2013-08-25 21:03:11
【问题描述】:

我有点困惑我们是否可以使用 _bstr_t 在 c# 和 C++ 之间传递字符串,反之亦然。

我使用 C++/CLI 作为 C# 和 C++ 之间的中间层。

如果可能,还请举例说明如何在 C# 端和 C++/CLI 端对它进行编组,因为没有太多相关文档

还建议更好的数据类型/机制来传递字符串。

【问题讨论】:

  • 在 C# 和 C++/CLI 之间,您可以使用 System::String^。至于 C++/CLI 和原生 C++ 之间,嗯……你的原生 C++ 代码需要什么?
  • 我需要以某种方式将字符串传递给本机 C++,那么我应该如何编组 System::String^。我应该选择原生 C++ 或其他数据类型的 char * 吗?我还需要将值从本机 C++ 传递回 C#。我该怎么做?
  • 你的意思是原生 C++ 需要 std::string?
  • 这取决于您的 C++ 代码和库。哪种字符串数据结构、字符集和编码最适合?数据结构将如何分配和释放?如果字符集不是 C# 使用的(Unicode),你想如何处理每个方向的不匹配?

标签: c# string c++-cli marshalling bstr


【解决方案1】:

根据 MSDN,这 应该 用于将 String^ 转换为字符串(这是迄今为止最简单的方法)。但是我无法测试,我的 VC++2008 Express 没有找到 Marshal.h...

// TestCppCli2008.cpp : main project file.

#include "stdafx.h"
#include <string>
#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>

using namespace System;
using namespace msclr::interop;

int main()
{
    System::String^ s = L"Hello World";

    std::string str = marshal_as<std::string>(s);
    return 0;
}

【讨论】:

  • 曾经有一个网站 marshal-as dot net,您可以在其中下载 marshal_as 模板内容,包括支持新数据类型的重载,这是在 Express Edition 上获取它的一种方式。不幸的是,注册似乎已过期,并且该域已被选为广告...
  • 顺便说一句,该文件应该包含在 VC++ 2010 Express 中,而不是 2008。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多