c# - 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()
函数中的文本输出到文本框?
解决方案
在 Windows 上(这WPF
意味着您正在使用),BSTR
可以从标准宽字符串创建,您可以尝试C++
以下代码:
#include <windows.h> // For BSTR from "wtypes.h" header.
extern "C" __declspec(dllexport) BSTR text_output()
{
return ::SysAllocString(L"something");
}
// ...
然后在你的声明中加入string
with ,比如:MarshalAs
C#
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;
}
推荐阅读
- kotlin - 对于 Kotlin 中的 List,asReversed() 本质上是 reversed() 吗?
- r - 如何定期刷新 R-Shiny 应用程序
- excel - 将循环结果拆分为vba中的范围
- reactjs - manifest.json 404(未找到)
- php - 从 SQL 数据库显示信息到谷歌图表
- java - JLayeredPane 破坏布局
- c# - TinyMCE:ASP.NET MVC
- python - 如何识别元组中的相同元素
- alfresco - 如何在 Alfresco 共享中动态禁用控制?
- c# - 在 .Net Framework 中存储和读取 app.config 中的自定义信息