[英]calling a C++ dll from C# throwing a SEHException
I am trying to call a dll, which I build in C++, from a C# code. 我正在尝试从C#代码调用一个用C ++构建的dll。 However, I am getting the following error:
但是,我收到以下错误:
Exception thrown: 'System.Runtime.InteropServices.SEHException' in dlltest_client.exe An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in dlltest_client.exe External component has thrown an exception.
引发异常:dlltest_client.exe中的“ System.Runtime.InteropServices.SEHException” dlltest_client.exe中发生了类型为“ System.Runtime.InteropServices.SEHException”的未处理异常外部组件引发了异常。
I am building the C++ dll using a cpp code which in turn imports a header file: 我正在使用cpp代码构建C ++ dll,而cpp代码又导入了头文件:
dlltest.cpp : 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_;
}
where dlltest.h : 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();
this successfully builds dlltest.dll 这将成功生成dlltest.dll
My C# code that is ought to utilise the dll is 我应该利用dll的C#代码是
dlltest_client.cs dlltest_client.cs
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport(@"path\dlltest.dll")]
private static extern void jigsaw_init(string full_input, string piece_input);
[DllImport(@"path\dlltest.dll")]
private static extern void findPiece();
static void Main(string[] args)
{
string full = @"path\monster_1.png";
string piece = @"path\piece01_01.png";
jigsaw_init(full, piece);
findPiece();
}
}
You cannot use C++ std::string
for unmanaged interop, which is the reason for your DLL throwing an exception. 您不能将C ++
std::string
用于非托管互操作,这是DLL引发异常的原因。
Instead use pointer to null-terminated character array to pass strings between your C# code and the unmanaged C++ code. 而是使用指向以null终止的字符数组的指针在C#代码和非托管C ++代码之间传递字符串。
The other error is that the C++ code uses cdecl calling convention, but the C# code assumes stdcall. 另一个错误是C ++代码使用cdecl调用约定,但是C#代码采用stdcall。 You need to make the two sides of the interface match, change one to match the other.
您需要使界面的两侧匹配,更改一侧以匹配另一侧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.