从C#调用C++dll引发SEHException

calling a C++ dll from C# throwing a SEHException

本文关键字:引发 SEHException C++dll 调用      更新时间:2023-10-16

我正试图从C#代码中调用一个用C++构建的dll。然而,我得到了以下错误:

引发异常:"系统。运行时。InteropServices。SEHExceptiondlltest_client.exe类型为的未处理异常’系统。运行时。InteropServices。SEHException"发生在dlltest_client.exe外部组件引发异常。

我正在使用cpp代码构建C++dll,该代码反过来导入一个头文件:

dlltest.cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include "dlltest.h"
using namespace std;
// DLL internal state variables:
static string full_;
static string piece_;
void jigsaw_init(const string full_input, const string piece_input)
{
full_ = full_input;
piece_ = piece_input;
}
void findPiece()
{
cout << full_;
cout << piece_;
}

其中dlltest.h

#pragma once
#ifdef DLLTEST_EXPORTS
#define DLLTEST_API __declspec(dllexport)
#else
#define DLLTEST_API __declspec(dllimport)
#endif
extern "C" DLLTEST_API void jigsaw_init(
const std::string full_input, const std::string piece_input);
extern "C" DLLTEST_API void findPiece();

这成功地构建了dlltest.dll

我的C#代码应该使用dll是

dlltest_client.cs

using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport(@"pathdlltest.dll")]
private static extern void jigsaw_init(string full_input, string piece_input);
[DllImport(@"pathdlltest.dll")]
private static extern void findPiece();
static void Main(string[] args)
{
string full = @"pathmonster_1.png";
string piece = @"pathpiece01_01.png";
jigsaw_init(full, piece);
findPiece();
}
}

不能将C++std::string用于非托管互操作,这是DLL引发异常的原因。

相反,使用指向以null结尾的字符数组的指针在C#代码和非托管C++代码之间传递字符串。

另一个错误是C++代码使用cdecl调用约定,但C#代码采用stdcall。您需要使界面的两侧匹配,将其中一个更改为与另一个匹配。