gpt4 book ai didi

由于导入 C++ DLL,C# ShowDialog() 抛出错误

转载 作者:行者123 更新时间:2023-11-28 03:46:23 28 4
gpt4 key购买 nike

此 C# 程序在不使用 showdialog() 的情况下工作正常,但当我尝试使用 showdialog() 时它会创建“系统访问冲突”异常。奇怪!!

C#代码

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

namespace w_CSharp_GUI_1
{
public partial class Form1 : Form
{
private String W_Addr,C_Addr,Pic_Addr="lol";

[DllImport("face_proj_trial_dll.dll")]
public static extern string f_detect(string path);

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog2 = new OpenFileDialog();

openFileDialog2.ShowDialog(this);

Pic_Addr = (f_detect("C:\\pic.jpg"));

textBox1.Text = Convert.ToString(Pic_Addr);
}

}
}

C++代码:

#include "face_detect_DLL.h"

extern "C" __declspec(dllexport) char* _stdcall f_detect(char* path)
{
return path;
}

最佳答案

这一点也不奇怪。您正在返回一个实际上由 C# 编码器创建的 C 字符串。编码器然后尝试两次释放该内存。一次作为返回值,一次作为传递给 DLL 的参数。第一次释放会失败,因为内存不是用 C# 编码器假定的分配器分配的。

无论如何,您只是不想从您的 DLL 返回 char*。我不确定你到底想做什么,但字符串 P/invokes 的正常模式是:

  1. 为了将字符串从 C# 编码到 C++,在 C# 中将它们声明为 string,在 C++ 中声明为 char*
  2. 反之则使用StringBuilder。在调用和使用 MarshalAs 之前分配缓冲区。网络上有无数这种模式的例子。

关于由于导入 C++ DLL,C# ShowDialog() 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7515481/

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