gpt4 book ai didi

c# - 如何在调用 WindowsPhoneRuntimeComponent 时使用字节数组作为参数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:14 24 4
gpt4 key购买 nike

首先大家好!我想从我的 Windows Phone 应用程序访问 2 个 C++ 函数。所以我遵循了 this 教程的每一步,并设法将该函数称为教程的海报。现在我想访问我自己的函数,所以我在标题和 .cpp 文件中创建了类,只要我的函数不公开,项目就可以正常构建。意味着我无法访问它们。

 public ref class Base64Encoding sealed
{
public:
char *EncodeData(char *data, int length, int *resultLength); //this doesnt compile
char *DecodeString(char *data, int *resultLength); //this compiles buts inaccessible
};

我收到一个返回异常,提示错误 C3992:公共(public)成员的签名包含无效类型 char。我做了一些谷歌搜索,据我所知我不能发送 char 类型的参数,因为它是非托管代码或类似的东西。

那么这里有什么问题呢?为什么我不能传递char类型的参数?

更新

我听从了 robwirving 的建议,现在标题看起来像这样。

public ref class Base64Encoding sealed
{
public : Platform::String^ EncodeData(String^ StringData);
public : Platform::String^ DecodeString(String^ StringData);
};

现在为了从 String^ StringData 参数中获取 char* 数据,我在我的 .cpp 中做了

#include <string>
#include <iostream>
#include <msclr\marshal_cppstd.h>
using namespace Platform;
using namespace std;
String^ EncodeData(String^ StringData)
{
// base64 lookup table. this is the encoding table for all 64 possible values
static char *figures = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
msclr::interop::marshal_context context;
std::string s = context.marshal_as<std::string>(StringData);
char *data = new char[s.size() + 1];
int length = s.length;
int *resultLength = s.length;
data[s.size()] = 0;
/* bla bla some functions irrelevant*/
.
.
.
return StringFromAscIIChars(result);
}

static String^ StringFromAscIIChars(char* chars)
{
size_t newsize = strlen(chars) + 1;
wchar_t * wcstring = new wchar_t[newsize];
size_t convertedChars = 0;
mbstowcs_s(&convertedChars, wcstring, newsize, chars, _TRUNCATE);
String^ str = ref new Platform::String(wcstring);
delete[] wcstring;
return str;
}

但现在我在构建时遇到了 2 个错误。

1:错误 C1114:WinRT 不支持托管程序集的#using

2:IntelliSense:不允许指向 C++/CX 映射引用类或接口(interface)类的普通指针

最佳答案

您在问题中说出了正确的答案。不能在 WinRT 组件的公共(public)函数中使用 char。但是,您可以使用字符串,我建议您将函数更改为以下内容:

public ref class Base64Encoding sealed
{
public:
Platform::String^ EncodeData(Platform::String^ data);
Platform::String^ DecodeString(Platform::String^ data);
};

在编码/解码函数的定义中,您可以将输入从 Platform::String^ 转换为 char 数组,调用原始 C++ 函数,然后将返回值转换回 Platform::String^

我知道这可能看起来像很多额外的工作,但它使将使用您的 WinRT 组件的 C# 的互操作变得容易得多。

更新:

我认为您的其他错误可能来自包含 msclr\marshal_cppstd.h 以及您将 Platform::String^ 转换为 std::string 的方式。

引用这篇文章了解如何从 Platform::String^ 转换为 char*:How to convert Platform::String to char*?

关于c# - 如何在调用 WindowsPhoneRuntimeComponent 时使用字节数组作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22411656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com