首页 > 解决方案 > 如何将 C++ 字符串从 C++dll 返回到 C# 应用程序

问题描述

我有一个 C# 应用程序使用的 C++ dll。我想将一个字符串从 C++ dll 返回到 C# 应用程序。下面是我的示例代码。 动态链接库

#include <iostream>
#include<comdef.h>
#include <iomanip>

#include <comutil.h> // #include for _bstr_t

extern "C" __declspec(dllexport) std::string getName();

std::string getName() {
    std::string _name = "XYZ";
    return _name;
}

C# 代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
     [DllImport("NativeLibrary.dll") ]
    public static extern string getName();
    private void btnAdd_Click(object sender, EventArgs e)
    {
        string res = getName();
        Console.WriteLine(res);
    }
}

我能够成功构建它,但是当我运行应用程序时没有任何反应。我怎么能摆脱这个问题?

标签: c#c++

解决方案


推荐阅读