【问题标题】:Pass string like parameter to external method as char *将类似参数的字符串作为 char * 传递给外部方法
【发布时间】:2016-10-09 02:39:42
【问题描述】:

我正在创建 Windows 运行时组件 (c++),以便稍后在 windows phone 8.1 应用程序 (c#) 中使用它。我的问题很简单,但我找不到任何答案:

我需要创建一个方法,将 string/char */anything 作为文件路径作为参数,并将其传递给以 char * 作为参数的外部方法。

我尝试过使用 std::string、String^、char *。但我仍然收到错误,例如不支持此类类型(不支持 String^ 情况)或其他类型。

是否有一些简单的答案可以告诉我该怎么做?

有错误的代码示例

开始

#include "pch.h"
#include "Class1.h"

using namespace Platform;

namespace WindowsRuntimeComponent2
{
    public ref class Class1 sealed
    {

各种类型:

int Foo(std::string param) {

原因:Foo': signature of public member contains native type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' WindowsRuntimeComponent2 和其他一些包含有关字符串依赖项的相同信息

int Foo(char * param) {

原因:'Foo': signature of public member contains native type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' WindowsRuntimeComponent2

int Foo(String^ photoPath) {

这不会导致任何错误,但我不知道如何将其解析为我的char *

【问题讨论】:

  • 您收到一条错误消息,指出 std::string 不受支持?
  • 您应该发布一些代码 (MCVE) 和出现的错误...
  • 什么字符编码?
  • 您使用哪种类型的调用约定?
  • 感谢你们的 cmets 伙计们,我添加了一些有错误的示例。

标签: c# c++ windows-runtime


【解决方案1】:

基本上这里你只需要知道如何从System.String^ 转换为std::string,这可以在C++/CLI 模式下完成,如下所示:

#include <msclr\marshal_cppstd.h>

//...

int Foo(String^ photoPath) {
    std::string unmanaged_photoPath = msclr::interop::marshal_as<std::string>(photoPath);
    // then convert to c-style string as normal using unmanaged_photoPath.c_str();
    return 0;
}

【讨论】:

  • 谢谢您的回答,我确信我更近了一步,但这种方法会导致一些集成问题:'c:\windows\microsoft.net\framework\v4.0.30319\mscorlib.dll' : WinRT does not support #using of a managed assembly WindowsRuntimeComponent2 在 vcclr.h 行:16。你知道如何处理它吗?
  • @MateuszRogulski 如果没有看到代码结构,我无法确定——line 16 在我的回答中是否对应于std::string unmanaged_photoPath = ...
  • @ArchibishopOfBanterbury 抱歉理解错误,vcclr.h 是 Windows 运行时组件的文件。在这一行中,我们有#using &lt;mscorlib.dll&gt;。所以我猜你的解析方式使用它。
猜你喜欢
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多