【发布时间】:2015-01-12 03:54:47
【问题描述】:
我有一个 C/C++ dll 并尝试使用 PInvoke 连接到 C# 应用程序。
我收到Debug assertion failed 错误。 dll 在与 C++ 应用程序接口时起作用,问题仅在与 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);
}
}
【问题讨论】:
-
头文件中的
__cplusplus测试完全没用,因为这些函数使用C 中不存在的类型。 -
问题中的非托管函数使用 cdecl 调用约定。 p/invoke 的默认值为 stdcall。