プロが教える店舗&オフィスのセキュリティ対策術

C++/CLIのFormでの開発なのですが、function(char *str)に起動時の引数を渡したいと考えたのですが、array<System::String ^>をchar型に変える方法が分からず、苦戦しております。
どうやったら良いのでしょうか?

エラーは次のように出ます。
CouponPrint.cpp(22): error C2664: 'PtrToStringChars' : 1 番目の引数を 'cli::array<Type> ^' から '__const_String_handle' に変換できません。(新しい機能 ; ヘルプを参照)
with
[
Type=System::String ^
]
この変換を実行可能なユーザー定義変換演算子がないか、または演算子を呼び出せません。

以下、そのときのソースコード
int main(array<System::String ^> ^args)
{
// コントロールが作成される前に、Windows XP ビジュアル効果を有効にします
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);

if(!args)
{
size_t convertedChars = 0;
size_t sizeInBytes = ((args->Length + 1) * 2);
const wchar_t *wch = PtrToStringChars(args);
char *ch = (char *)malloc(sizeInBytes);
errno_t err = 0;
err = wcstombs_s(&convertedChars,
ch, sizeInBytes,
wch, sizeInBytes);
if (err != 0)
printf_s("wcstombs_s failed! \n");

function(ch);

free(ch);
}
// メイン ウィンドウを作成して、実行します
Application::Run(gcnew Form1());
return 0;
}

A 回答 (5件)

> marshal_context ^ context = gcnew marshal_context();



marshal_contextをgcnewする必要はなさそう。

#include <msclr/marshal.h>
#include <cstdio>
#include <cstring>

using namespace System;
using namespace msclr::interop;

void a(const char* s) {
 std::printf( "%s(%d)%p\n", s, std::strlen(s), s );
}

int main(array<String^>^ args) {
 marshal_context ctx;
 for each (String^ s in args ) {
  a(ctx.marshal_as<const char*>(s));
 }
}
    • good
    • 0
この回答へのお礼

ソースコードを添えていただきありがとうございます。無事動作できることを確認しました。

お礼日時:2010/11/21 19:23

C++/CLIのコードって書いたことないけど、Visual Studio 2008とMSDN、googleの力を借りて書いてみたり:



/* http://support.microsoft.com/kb/311259/ja */

#include <msclr/marshal.h>
#include <stdio.h>
#include <string.h>

using namespace System;
using namespace msclr::interop;

void a( const char* s ){ printf( "%s(%d)%p\n", s, strlen(s), s ); }

int main(array<System::String ^> ^args){
marshal_context ^ context = gcnew marshal_context();
for each ( System::String ^s in args ){ a( context->marshal_as<const char*>( s ) ); }
delete context;
}

以上、1時間かかったり。
    • good
    • 0
この回答へのお礼

わざわざ、ありがとうございます。
MSDNにそういうことを書いてあるとは思いもよりませんでした。
次から気をつけます。

お礼日時:2010/11/21 19:17

下記URL参照。



参考URL:http://codezine.jp/article/detail/4774
    • good
    • 0
この回答へのお礼

ありがとうございます。確認してみましたが、何が何やらさっぱりでした。

お礼日時:2010/11/21 19:15

>if(!args)



ここの ! が不要ではないかと考えるのは、素人の浅はかな考えでしょうか。


# 個人的には、1つの文の中で「~ですが、~ですが、…」と続けるのは悪文だと思う。
    • good
    • 0
この回答へのお礼

確かに、不要でしたね。ご指摘ありがとうございます。

お礼日時:2010/11/21 01:15

「array<System::String ^> ^」ってことは, ひらたくいうと「文字列の配列」ってことだ.


それを「char型に変える」というのは, いったいどのようなものに対してどのような結果を期待しているのでしょうか?

この回答への補足

文字列の配列でも、array<System::String ^> ^とchar*とは構造が違うため、
質問で出ている関数に値を渡せないのですが・・・。

補足日時:2010/11/21 01:19
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!