问题描述
我正在尝试在 C# 程序中加载 C++ DLL,但是在 C# 中加载时来自 C++ 的变量已损坏(我认为)
这就是输出的样子(这是 C++)
//cout << "Loading config,please wait..." << endl;
LoadConfig();
Sleep(2000);
clear();
cout << "Your current settings are: " << endl << endl;
cout << "Resolution: " << screen_width << "x" << screen_height << endl;
cout << "Sensitivty: " << sensitivity << endl;
cout << "Smoothing: " << smoothing << endl;
cout << "FOV: " << fov << endl;
cout << "Mode: " << mode << endl;
cout << "Color: " << color << endl;
cout << "MB4: " << mb4 << endl;
cout << "MB5: " << mb5 << endl;
cout << "lClick: " << lClick << endl;
cout << "Hold : " << hold << endl;
Sleep(10000);
这就是它实际的样子。
Resolution: 1920x1080
Sensitivty: 1
Smoothing: 1e-07
FOV: 100Your current settings are:
Mode:
1Resolution:
1920x1080Color: PURPLE
Sensitivty: 1
MB4: Smoothing: 1e-071
FOV: 100
MB5:
0
Mode: 1lClick: 0
Hold : 1Color: PURPLE
MB4: 1
MB5: 0
lClick: 0
Hold : 1
The program '[288] GynLockLoader.exe' has exited with code -1073741510 (0xc000013a).
为什么会这样? C++ 中的变量是正确的,我通过配置加载器加载它们 LoadConfig();
LoadConfig()(不要介意乱七八糟的代码,我不经常使用C++)
void LoadConfig() {
ifstream cFile("config.txt");
if (cFile.is_open())
{
string line;
while (getline(cFile,line))
{
line.erase(remove_if(line.begin(),line.end(),isspace),line.end());
if (line.empty() || line[0] == '#')
{
continue;
}
auto delimiterPos = line.find("=");
string name = line.substr(0,delimiterPos);
string value = line.substr(delimiterPos + 1);
if (name == "resX") {
screen_width = stoi(value);
}
else if (name == "resY") {
screen_height = stoi(value);
}
else if (name == "sensitivity") {
sensitivity = stod(value);
}
else if (name == "smoothing") {
smoothing = stod(value);
}
else if (name == "fov") {
fov = stoi(value);
}
else if (name == "mode") {
mode = stoi(value);
}
else if (name == "color") {
color = value;
}
else if (name == "mb4") {
if (value == "1") {
mb4 = true;
}
else {
mb4 = false;
}
}
else if (name == "mb5") {
if (value == "1") {
mb5 = true;
}
else {
mb5 = false;
}
}
else if (name == "lClick") {
if (value == "1") {
lClick = true;
}
else {
lClick = false;
}
}
else if (name == "hold") {
if (value == "1") {
hold = true;
}
else {
hold = false;
}
}
}
}
else
{
cerr << "Couldn't open config file for reading.\n";
}
}
我在 dllmain.h 中调用 extern C,因此我可以通过调用 DllImport 在 C# 中使用 main()
dllmain.h
extern "C"
__declspec(dllexport)
int
main(void);
这就是我在 C# 中调用 main()
的方式
C# main();
static class Program
{
[DllImport("GynLock.dll")]
public static extern void main();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Main());
main();
}
}
一切正常加载,我只是不明白为什么我的输出看起来如此奇怪和损坏(?)
有人可以帮我澄清一下吗,也许我在这里遗漏了一些基本的东西...
解决方法
c++ force std::cout flush (print to screen)
将 (std::)flush 添加到每个文件的末尾。当您将它与 c# 混合使用时,可能有多种原因。如果您有 github 项目 - 告诉我,我会尽力提供帮助。干杯。
cout << "Your current settings are: " << endl << endl << flush;