2

プラットフォームの呼び出しを使用して、C#からC++に文字列を渡そうとしています。

  • C ++コード:

    #include<string>
    using namespace std;
    
    extern "C" 
    {
         double __declspec(dllexport) Add(double a, double b)
         {
             return a + b;
         }
         string __declspec(dllexport) ToUpper(string s)
         {
             string tmp = s;
             for(string::iterator it = tmp.begin();it != tmp.end();it++)
                 (*it)-=32;
             return tmp;
         }
    }
    
  • C#コード:

    [DllImport("TestDll.dll", CharSet = CharSet.Ansi, CallingConvention =CallingConvention.Cdecl)]
    public static extern string ToUpper(string s); 
    
    static void Main(string[] args)
    {
        string s = "hello";
        Console.WriteLine(Add(a,b));
        Console.WriteLine(ToUpper(s));
    }
    

SEHExceptionを受け取ります。このように使うことは不可能std::stringですか?char*代わりに使用する必要がありますか?

4

3 に答える 3

-2

char*を使用することをお勧めします。ここに可能な解決策があります。

次のように別のC#関数ToUpper_2を作成する場合

C#側:

[DllImport("TestDll.dll"), CallingConvention = CallingConvention.Cdecl]
private static extern IntPtr ToUpper(string s);

public static string ToUpper_2(string s) 
{
    return Marshal.PtrToStringAnsi(ToUpper(string s));
}

C ++側:

#include <algorithm>
#include <string>

extern "C" __declspec(dllexport) const char* ToUpper(char* s) 
{
    string tmp(s);

    // your code for a string applied to tmp

    return tmp.c_str();
}

完了です!

于 2012-11-22T14:39:13.017 に答える