C ++将字符串传递给C#dll

时间:2013-08-27 03:21:56

标签: c# c++ string

我有一个C ++应用程序通过wrapper.cpp在C#dll中调用WORD(name,cpu)函数,它包含一个错误。谁能帮我?提前谢谢。

  

错误C2664:'CsharpDLL :: WORD':无法将参数1从'std :: string'转换为'System :: String ^'

C ++应用程序

extern "C" _declspec(dllimport) void _stdcall WORD(string name, string cpu);

int main()
{
    string name="f";
    string cpu="F";

    WORD(name,cpu);
}

wrapper.cpp

extern "C" _declspec(dllexport) void _stdcall WORD(string name ,string cpu)
{
    return CsharpDLL::WORD(name,cpu);  // <-- Error here
}

C#dll

public class CsharpDLL
{
    public static void WORD(string name, string cpu)
    {
    if(cpu=="add")
    {
        Console.WriteLine("aa");
    }
}

1 个答案:

答案 0 :(得分:1)

你需要从传递给你的包装函数的每个System::String的字符数组中构造一个std::string

extern "C" _declspec(dllexport) void _stdcall WORD(string name ,string cpu)
{
    System::String ^managedName = gcnew System::String(name.c_str());
    System::String ^managedCpu = gcnew System::String(cpu.c_str());

    return CsharpDLL::WORD(managedName, managedCpu);
}