从C#调用C++dll引发SEHException
calling a C++ dll from C# throwing a SEHException
我正试图从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。您需要使界面的两侧匹配,将其中一个更改为与另一个匹配。
相关文章:
- boost::进程间消息队列引发错误
- 孤立代码块在结构中引发异常
- 大于65535的C++数组[size]引发不一致的溢出
- cppcheck在const std::string[]上引发警告
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- C++中函数的向量返回类型引发错误
- 在另一个线程中调用luaL_error会引发qWarning
- 尝试使用智能指针时引发异常
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- 在 C++/CLI 中将 .NET 事件从一个 DLL 引发到另一个 DLL
- 如果分配数组引发异常,是否应该释放该数组
- 在调试模式下引发C++ "deque iterator not dereferencable"异常
- 迭代器类的重载前缀增量运算符会引发分段错误
- 引发异常的方法的命名约定 (C++)?
- 在 Boost::fiber 中引发的BOOST_ASSERT故障 Visual Studio "Debug" 构建
- 读取文件时引发异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 从 C++ 中异常的构造函数引发异常
- cout 新创建的对象引发运行时错误
- 从C#调用C++dll引发SEHException