首页 > 解决方案 > C++ DLL 的函数不在 WPF 中输出文本

问题描述

我试图将文本从 C++ 函数输出到 WPF 中的文本框,但是当我单击按钮时它什么也不输出。在 C# 控制台中它工作。

这里是来自 C# 控制台的代码:

namespace ConsoleApp1
{

    class Program
    {
        const string dllfile = "C:\\...";
        [DllImport(dllfile, EntryPoint = "main", CallingConvention = CallingConvention.Cdecl)]
        private static extern string text_output();

        static void Main(string[] args)
        {
            text_output();
        }
    }
}

这里是来自 C++ DLL 的代码:

using namespace std;


void text_output();
void text_output()
{
    cout << "something" << endl;
}

extern "C" __declspec(dllexport) int main()
{
    text_output();
    return 0;
}

这里是来自 C# WPF 页面的代码:

namespace application
{
    public partial class Page1 : Page
    {
        const string dllfile = "C:\\...";
        [DllImport(dllfile, EntryPoint = "main", CallingConvention = CallingConvention.Cdecl)]
        private static extern string text_output();
        
        public Page1()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            txtBox.Text += text_output();
        }
        
    }
}

当我单击按钮时,我该怎么做才能将text_output()函数中的文本输出到文本框?

标签: c#c++wpfdll

解决方案


在 Windows 上(这WPF意味着您正在使用),BSTR可以从标准宽字符串创建,您可以尝试C++以下代码:

#include <windows.h> // For BSTR from "wtypes.h" header.

extern "C" __declspec(dllexport) BSTR text_output()
{
    return ::SysAllocString(L"something");
}

// ...

然后在你的声明中加入stringwith ,比如:MarshalAsC#

const string dllfile = "C:\\...";
[DllImport(dllfile, EntryPoint = "main", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string text_output();

PS您可能需要转换char *为宽字符串,例如:

BSTR StrToBSTR(const char *value) {
    int valueLength = lstrlenA(value);
    if (valueLength > 0) {
        int resultLength = ::MultiByteToWideChar(CP_ACP, 0, value, valueLength, NULL, 0);
        if (resultLength > 0) {
            BSTR result = ::SysAllocStringLen(0, resultLength);
            ::MultiByteToWideChar(CP_ACP, 0, value, valueLength, result, resultLength);
            return result;
        }
    } 
    return NULL;
}

推荐阅读