gpt4 book ai didi

c# - 从 DLL 文件调用消息框函数时出现奇怪的字符?

转载 作者:行者123 更新时间:2023-11-28 02:06:09 25 4
gpt4 key购买 nike

当从用C++编译的dll文件调用函数时,我看到一个问题,函数代码如下的dll文件:

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>

char* str;
int _stdcall inputt(char* str_)
{
str=str_;
return 1;
}

int _stdcall Shooow()
{
MessageBoxA(NULL,str,"Message...",MB_OK);
return 0;
}

在此,我导出了两个函数 inputt() 和 Shooow()。名为“TestCCCC.dll”的 DLL 文件。然后我在 C# 代码中调用它们如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace muWrapper
{
public partial class WndSample : Form
{
[DllImport("TestCCCC.dll")]
private static extern int inputt(string FuncName);
[DllImport("TestCCCC.dll")]
private static extern int Shooow();

public WndSample()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int ret = inputt("aaaaaa");
ret = Shooow();
}
}
}

当我运行它时,第一次单击按钮时,它会显示一个带有奇怪字符的消息框,而不是“aaaaaa”!!!?继续点击第二次,真实显示“aaaaaa”,继续……真实真实显示……

告诉我这个问题发生了什么?如何编写两个函数inputt()和Shooow()第一时间真实显示?谢谢。

最佳答案

inputt 被传递一个指向临时字符串的指针。您不能只保存指针,您需要保存整个字符串的拷贝。使用 std::string

最简单
#include "stdafx.h"
#include <windows.h>
#include <string>

static std::string str;
int _stdcall inputt(const char* str_)
{
str=str_;
return 1;
}

int _stdcall Shooow()
{
MessageBoxA(NULL,str.c_str(),"Message...",MB_OK);
return 0;
}

C# 原生支持 Unicode 字符串。如果要处理任意字符串,则需要将 DLLImport 行更改为:

    [DllImport("TestCCCC.dll", CharSet = Unicode)]
private static extern int inputt(string FuncName);

然后将 C++ 更改为:

#include "stdafx.h"
#include <windows.h>
#include <string>

static std::wstring str; // wide string
int _stdcall inputt(const wchar_t* str_) // wide char pointer.
{
str=str_;
return 1;
}

int _stdcall Shooow()
{
MessageBoxW(NULL,str.c_str(),L"Message...",MB_OK); // Use W version and long title.
return 0;
}

关于c# - 从 DLL 文件调用消息框函数时出现奇怪的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com