[英]Debug assertion failed using PInvoke to interface C/C++ DLL
我有一個C / C ++ dll,並嘗試使用PInvoke連接到C#應用程序。 我收到了Debug assertion failed
錯誤。 當連接到C ++應用程序時dll可以工作,問題僅在於連接到C#應用程序時。 我的DLL的.h和.cpp文件是
頭文件
#include <string>
#include <fstream>
#include <iostream>
#ifdef DLL_EXPORTS
#define DLL_EXPORTS __declspec(dllexport)
#else
#define DLL_EXPORTS __declspec(dllimport)
#endif
#define PASS 0
#define FILECREATE_FAIL 1
#define CAMERA_ERROR 2
#define MAX_NUM_FRAMES 10000
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
// Returns pass 0
// Fails 1
// Open the file at the path and start acquisition
DLL_EXPORTS int start_acquisition(string path);
DLL_EXPORTS int stop_acquisition();
#ifdef __cplusplus
}
#endif
CPP文件
#include "stdafx.h"
#include "IntensityDll.h"
#include <sstream>
ofstream fileout;
int counter;
char Header[64];
short Image[MAX_NUM_FRAMES][6400];
int ret;
int acquisition();
int start_acquisition(std::string path)
{
ret = PASS;
try
{
fileout.open(path);//fstream
if (fileout.is_open()) {
ret = acquisition();
}
}
catch(fstream::failure e)
{
cout << "Exception opening/reading file. " << endl;;
return FILECREATE_FAIL;
}
return ret;
}
錯誤信息如下圖所示。
我使用了PInvoke如下
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
[DllImport("C:\\WindowsFormsApplication1\\WindowsFormsApplication1\\Wavelength_MaxIntensityDll.dll")]
public static extern int start_acquisition(string path);
[DllImport("C:\\WindowsFormsApplication1\\Wavelength_MaxIntensityDll.dll")]
public static extern int stop_acquisition();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int ret = start_acquisition("C:\\Users\\nyan2012\\Desktop\\Wavelength_test\\test1.txt");
}
}
}
編輯1:我展示了使用PInvoke的示例。 與我的有什么不同?
class PlatformInvokeTest
{
[DllImport("user32.dll")]
public static extern int MessageBoxA(
int h, string m, string c, int type);
public static int Main()
{
return MessageBoxA(0, "Hello World!", "My Message Box", 0);
}
}
您沒有顯示p / invoke聲明,但是有100%的機會會出錯,因為沒有正確的聲明。 這些函數的簽名是特定於C ++的,因此不能直接從C#調用。
調試斷言跳閘是因為C ++函數實際上不是一個參數時,它試圖將其參數用作std::string
。 std::string
析構函數在范圍的末尾運行,嘗試釋放內存...並失敗,因為內存不是由std::string
構造函數分配的,因為不存在std::string
對象在這里 。
您可能添加了一個包裝器,該包裝器接受一些與p / invoke兼容的字符串類型,例如const char*
或BSTR
,創建一個std::string
,然后調用實函數。
實際上,從其他C ++編譯器或版本調用它也將遇到麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.