首先,嘿伙计们!我想从我的Windows手机应用程序访问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:公共成员的签名包含无效的类型char。 我做了一些谷歌搜索,据我所知,我不能发送类型char的参数,因为它的非托管代码或类似的东西。
那么这里的问题是什么?为什么我不能传递char类型的参数?
的更新 的
我遵循了抢劫的建议,现在标题看起来像这样。
public ref class Base64Encoding sealed
{
public : Platform::String^ EncodeData(String^ StringData);
public : Platform::String^ DecodeString(String^ StringData);
};
现在按顺序从我的.cpp
中的String ^ StringData参数中获取char *数据#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不支持#use of managed assembly
2:IntelliSense:不允许指向C ++ / CX映射ref类或接口类的普通指针
答案 0 :(得分:1)
你在问题中说了答案。您不能在WinRT组件的公共函数中使用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 ^ < / p>
我知道这可能看起来像是一项额外的工作,但它会让使用WinRT组件的C#更容易互操作。
<强>更新强>
我认为您的其他错误可能来自包含msclr \ marshal_cppstd.h以及您将Platform :: String ^转换为std :: string的方式。
参考这篇文章,了解如何从Platform :: String ^转换为char *:How to convert Platform::String to char*?